【问题标题】:Sharing an object between Gunicorn workers, or persisting an object within a worker在 Gunicorn 工作人员之间共享一个对象,或者在一个工作人员中持久化一个对象
【发布时间】:2013-04-12 02:27:49
【问题描述】:

我正在使用 Nginx / Gunicorn / Bottle 堆栈编写一个 WSGI 应用程序,该堆栈接受一个 GET 请求,返回一个简单的响应,然后向 RabbitMQ 写入一条消息。如果我通过直接的 Bottle 运行应用程序,那么每次应用程序收到 GET 时,我都会重用 RabbitMQ 连接。但是,在 Gunicorn 中,工作人员似乎每次都在销毁和重新创建 MQ 连接。我想知道是否有重用该连接的好方法。

更多详细信息:

##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()

【问题讨论】:

    标签: python bottle gunicorn


    【解决方案1】:

    好的,这花了我一点时间来整理。发生的情况是,每次收到新请求时,Gunicorn 都会运行我的 index() 方法,并因此创建 MQConnector 的新实例。

    解决方法是重构MQConnector,使其不再是一个类,而是一堆方法和变量。这样,每个工作人员每次都引用 same MQConnector,而不是创建一个新的 MQConnector 实例。最后,我通过了 MQConnector 的publish() 函数。

    #Bottle app
    from blah import blahblah
    import MQConnector
    
    @route('/')
    def index():
      blahblah(foo, bar, baz, MQConnector.publish)
    

    #MQConnector
    import pika
    mq_ip = "blah"
    exhange_name="blahblah"
    
    connection=pika.BlockingConnection(....
    ...
    
    def publish(message, r_key):
      ...
    

    结果:过去需要 800 毫秒的调用现在需要 4 毫秒。我曾经在 90 名 Gunicorn 工作人员中以每秒 80 次调用的最高速度,现在在 5 名 Gunicorn 工作人员中的最高调用次数约为 700 次/秒。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 2017-03-02
      • 2017-08-23
      • 1970-01-01
      • 2017-03-28
      • 2018-11-16
      • 1970-01-01
      相关资源
      最近更新 更多