如何在Pyramid应用程序中管理Rabbit-mq连接?
我想在Web应用程序的整个生命周期内重新使用与队列的连接。当前,我为每个发布调用打开/关闭队列的连接。
但是我在Pyramid中找不到任何“全局”服务定义。任何帮助表示赞赏。
金字塔不需要“全局服务定义”,因为您可以在普通的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
...
connection.do_stuff(foo, bar, baz)
拥有全局(任何全局)会在多线程环境中运行您的应用程序时引起问题,但是如果您运行多个processes会很好,所以这不是一个很大的限制。如果需要使用线程,可以将配方扩展为使用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,该应用程序将无法自动恢复。您需要以某种方式检测无效连接并重新连接。
看起来您可以使用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()
不过,在这种情况下,您需要谨慎对待线程/派生(每个线程/进程将需要自己的连接)。另外,请注意,我对金字塔不是很熟悉,可能会有更好的方法来进行此操作。