2014-04-04 32 views
0

我在嘗試使用Redis lpush/blpop同步傳入連接。使用Redis同步Django中的請求

例如,一個用戶嘗試加載頁面,並通過blpop連接他的連接塊。 只要第二位用戶開始加載頁面,他們就會釋放第一個連接。

取而代之的是第一個blpop似乎阻止整個服務器,第二個連接永遠不會進入視圖。

這裏是一個小例子,我嘗試:

views.py:

from django.http import HttpResponse 
import redis 

r = redis.StrictRedis() 

def two_view(request): 
    print('Starting request') 
    if r.get('waiting') == '1': 
     print('Someone is waiting') 
     r.set('waiting', 0) 
     print('Pushing key') 
     r.lpush('waiting_key', 1) 
     return HttpResponse('Released lock, we both go') 
    else: 
     print('Nobody is waiting.') 
     r.set('waiting', 1) 
     print('Begin waiting for other') 
     r.blpop('waiting_key') 
     return HttpResponse('set waiting higher, to: {}'.format(r.get('waiting'))) 

manage.py:

#!/usr/bin/env python 
from gevent import monkey 
monkey.patch_all() 
import os 
import sys 

if __name__ == "__main__": 
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "basic.settings") 

    from django.core.management import execute_from_command_line 

    execute_from_command_line(sys.argv) 

urls.py:

from django.conf.urls import patterns, include, url 
from django.contrib import admin 
from views import two_view 

admin.autodiscover() 

urlpatterns = patterns('', 
    url(r'^admin/', include(admin.site.urls)), 
    url(r'^$', two_view), 
) 

當我點兩下輸出標籤在它:

(env)Vincents-MacBook-Pro:basic vkhougaz$ python manage.py runserver 
Validating models... 

0 errors found 
April 04, 2014 - 02:38:34 
Django version 1.6.2, using settings 'basic.settings' 
Starting development server at http://127.0.0.1:8000/ 
Quit the server with CONTROL-C. 
Starting request 
Nobody is waiting. 
Begin waiting for other 

而且兩個標籤永遠不會完成加載。

這裏是什麼,我試圖做一個工作示例:

import redis 
from gevent import monkey 
import gevent 
monkey.patch_all(thread=False) 
from time import sleep 

conpol = redis.ConnectionPool() 

def do_lock_thing_1(): 
    r = redis.StrictRedis(connection_pool=conpol) 
    print('starting thing 1') 
    r.blpop('k') 
    print('finishing thing 1') 

def do_lock_thing_2(): 
    r = redis.StrictRedis(connection_pool=conpol) 

    print('starting thing 2') 
    sleep(1) 
    r.lpush('k', 1) 
    print('finishing thing 2') 

r2 = redis.StrictRedis(connection_pool=conpol) 

r2.delete('k') 

t1 = gevent.spawn(do_lock_thing_1) 
t2 = gevent.spawn(do_lock_thing_2) 

gevent.joinall([t1, t2]) 

和輸出:

starting thing 1 
starting thing 2 
<1 second delay> 
finishing thing 2 
finishing thing 1 

我缺少什麼?

回答