Python 金字塔web应用中的Rabbitmq连接管理?
如何在金字塔应用程序中管理我的rabbit mq连接 我希望在web应用程序的整个生命周期中重复使用与队列的连接。目前,我正在为每个发布调用打开/关闭与队列的连接Python 金字塔web应用中的Rabbitmq连接管理?,python,rabbitmq,pyramid,Python,Rabbitmq,Pyramid,如何在金字塔应用程序中管理我的rabbit mq连接 我希望在web应用程序的整个生命周期中重复使用与队列的连接。目前,我正在为每个发布调用打开/关闭与队列的连接 但我在金字塔中找不到任何“全球”服务的定义。非常感谢您的帮助。看起来您可以使用添加请求方法将对象附加到请求 下面是一个小示例应用程序,它使用该方法在启动时与套接字建立一个且仅一个连接,然后使该连接可用于每个请求: from wsgiref.simple_server import make_server from pyramid.co
但我在金字塔中找不到任何“全球”服务的定义。非常感谢您的帮助。看起来您可以使用
添加请求方法将对象附加到请求
下面是一个小示例应用程序,它使用该方法在启动时与套接字建立一个且仅一个连接,然后使该连接可用于每个请求:
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()
从wsgiref.simple\u服务器导入make\u服务器
从pyramid.config导入配置程序
从pyramid.response导入响应
def索引(请求):
返回响应('我有一个id为{}的持久连接:{}'。格式(
repr(request.conn).replace(“Pyramid”不需要“全局服务定义”,因为您可以在普通Python中轻松地执行此操作:
db.py:
connection = None
def connect(url):
global connection
connection = FooBarBaz(url)
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
您的启动文件(\uuuuu init\uuuuuuu.py
)
其他地方:
from db import connection
...
connection.do_stuff(foo, bar, baz)
from db import get_connection
get_connection().do_stuff(foo, bar, baz)
有一个全球(任何全球)如果您曾经在多线程环境中运行应用程序,则会导致问题,但如果您运行多个进程,则完全可以,因此这不是一个巨大的限制。如果您需要使用线程,则可以扩展配方以使用。下面是另一个示例,当第一次需要连接时,它也会延迟连接
db.py:
connection = None
def connect(url):
global connection
connection = FooBarBaz(url)
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 connection
...
connection.do_stuff(foo, bar, baz)
from db import get_connection
get_connection().do_stuff(foo, bar, baz)
长寿命连接的另一个常见问题是,如果在应用程序运行时重新启动RabbitMQ,应用程序将无法自动恢复。您需要以某种方式检测死连接并重新连接