2015-02-23 117 views
1

如何管理金字塔中的應用我的兔子,MQ連接?金字塔網絡應用程序中的Rabbitmq連接管理?

我想重新使用整個Web應用程序的生命週期到隊列連接。目前,我正在爲每次發佈呼叫打開/關閉隊列連接。

但我找不到任何在金字塔「全球」的服務定義。任何幫助讚賞。

回答

0

看起來你可以將對象與add_request_method請求。

下面是一個使用該方法,使一個且只有一個連接上啓動一個插座一個小例子程序,然後對每個請求的可用連接:

from wsgiref.simple_server import make_server 
from pyramid.config import Configurator 
from pyramid.response import Response 

def index(request): 
    return Response('I have a persistent connection: {} with id {}'.format(
     repr(request.conn).replace("<", "&lt;"), 
     id(request.conn), 
    )) 

def add_connection(): 
    import socket 
    s = socket.socket() 
    s.connect(("google.com", 80)) 
    print("I should run only once") 
    def inner(request): 
     return s 
    return inner 

if __name__ == '__main__': 
    config = Configurator() 
    config.add_route('index', '/') 
    config.add_view(index, route_name='index') 
    config.add_request_method(add_connection(), 'conn', reify=True) 
    app = config.make_wsgi_app() 
    server = make_server('0.0.0.0', 8080, app) 
    server.serve_forever() 

你需要小心線程/在這種情況下分叉(每個線程/進程將需要自己的連接)。另外請注意,我對金字塔不是很熟悉,可能有更好的方法來做到這一點。

2

金字塔並不需要一個 「全球性的服務定義」,因爲你可以平凡做,在普通的Python:

db.py:

connection = None 

def connect(url): 
    global connection 
    connection = FooBarBaz(url) 

你的啓動文件(__init__.py

from db import connect 
if __name__ == '__main__': 
    connect(DB_CONNSTRING) 

其他地方:

from db import connection 
... 
conenction.do_stuff(foo, bar, baz) 

具有全局(任何全局)會造成問題,如果你曾經運行在多線程環境中的應用程序,但是是完全沒有問題,如果你運行多個過程,所以它不是一個巨大的限制。如果您需要使用線程,配方可以擴展爲使用thread-local variables。這是另一個例子,當第一次需要連接時,它也會懶散地連接。

db.py:

import threading 

connections = threading.local() 

def get_connection(): 
    if not hasattr(connections, 'this_thread_connection'): 
     connections.this_thread_connection = FooBarBaz(DB_STRING) 
    return connections.this_thread_connection 

別處:

from db import get_connection 

get_connection().do_stuff(foo, bar, baz) 

與長期生活的連接另一個常見的問題是,應用程序將無法比如說,如果你重新啓動RabbitMQ的同時自動恢復你的應用程序在運行。您需要以某種方式檢測死連接並重新連接。