简体   繁体   English

在Gunicorn工作人员之间共享一个对象,或者在工作者中持久存在一个对象

[英]Sharing an object between Gunicorn workers, or persisting an object within a worker

I'm writing a WSGI app using an Nginx / Gunicorn / Bottle stack that accepts a GET request, returns a simple response, and then writes a message to RabbitMQ. 我正在使用Nginx / Gunicorn / Bottle堆栈编写WSGI应用程序,该堆栈接受GET请求,返回简单响应,然后将消息写入RabbitMQ。 If I were running the app through straight Bottle, I'd be reusing the RabbitMQ connection every time the app recieves a GET. 如果我通过直接的瓶子运行应用程序,每次应用程序收到GET时我都会重用RabbitMQ连接。 However, in Gunicorn, it looks like the workers are destroying and recreating the MQ connection every time. 但是,在Gunicorn中,工作人员似乎每次都在破坏并重新创建MQ连接。 I was wondering if there's a good way to reuse that connection. 我想知道是否有一种重用该连接的好方法。

More detailed info: 更详细的信息:

##This is my bottle app
from bottle import blahblahblah
import bottle
from mqconnector import MQConnector

mqc = MQConnector(ip, exchange)

@route('/')
def index():
  try:
    mqc
  except NameError:
    mqc = MQConnector(ip, exchange)

  mqc.publish('whatever message')
  return 'ok'

if __name__ == '__main__':
  run(host='blah', port=808)
app = bottle.default_app()

Okay, this took me a little while to sort out. 好的,这花了我一点时间来整理。 What was happening was, every time a new request came through, Gunicorn was running my index() method and, as such, creating a new instance of MQConnector . 发生的事情是,每次发出新请求时,Gunicorn都在运行我的index()方法,因此创建了一个新的MQConnector实例。

The fix was to refactor MQConnector such that, rather than being a class, it was just a bunch of methods and variables. 修复是重构MQConnector ,而不是一个类,它只是一堆方法和变量。 That way, each worker referred to the same MQConnector every time, rather than creating a new instance of MQConnector. 这样,每个工作程序每次都引用相同的 MQConnector,而不是创建MQConnector的新实例。 Finally, I passed MQConnector's publish() function along. 最后,我传递了MQConnector的publish()函数。

#Bottle app
from blah import blahblah
import MQConnector

@route('/')
def index():
  blahblah(foo, bar, baz, MQConnector.publish)

and

#MQConnector
import pika
mq_ip = "blah"
exhange_name="blahblah"

connection=pika.BlockingConnection(....
...

def publish(message, r_key):
  ...

Results: A call that used to take 800ms now takes 4ms. 结果:过去需要800毫秒的呼叫现在需要4毫秒。 I used to max out at 80 calls/second across 90 Gunicorn workers, and now I max out around 700 calls/second across 5 Gunicorn workers. 我曾经在90名Gunicorn工作人员中以每秒80次呼叫最大速度,而现在我在5名Gunicorn工作人员中最多可以发出约700次呼叫/秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM