如何管理金字塔中的应用我的兔子,MQ连接?金字塔网络应用程序中的Rabbitmq连接管理?
我想重新使用整个Web应用程序的生命周期到队列连接。目前,我正在为每次发布呼叫打开/关闭队列连接。
但我找不到任何在金字塔“全球”的服务定义。任何帮助赞赏。
如何管理金字塔中的应用我的兔子,MQ连接?金字塔网络应用程序中的Rabbitmq连接管理?
我想重新使用整个Web应用程序的生命周期到队列连接。目前,我正在为每次发布呼叫打开/关闭队列连接。
但我找不到任何在金字塔“全球”的服务定义。任何帮助赞赏。
看起来你可以将对象与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("<", "<"),
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()
你需要小心线程/在这种情况下分叉(每个线程/进程将需要自己的连接)。另外请注意,我对金字塔不是很熟悉,可能有更好的方法来做到这一点。
金字塔并不需要一个 “全球性的服务定义”,因为你可以平凡做,在普通的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的同时自动恢复你的应用程序在运行。您需要以某种方式检测死连接并重新连接。