如何使用eventlet库为异步gunicorn工作者

时间:2016-08-10 14:51:30

标签: python django gunicorn eventlet green-threads

我的一个django项目是使用 ansible(gunicorn& nginx)部署的。以下是 gunicorn 配置:

bind = '127.0.0.1:8001'
backlog = 2048

workers = 8
worker_class = 'sync'
worker_connections = 1000
timeout = 300
keepalive = 2

spew = False

daemon = False
pidfile = None
umask = 0
user = None
group = None
tmp_upload_dir = None

loglevel = 'info'
errorlog = '/var/log/error.log'
accesslog = '/var/log/access.log'

proc_name = None

def pre_fork(server, worker):
    pass

def pre_exec(server):
    server.log.info("Forked child, re-executing.")

def when_ready(server):
    server.log.info("Server is ready. Spawning workers")

def worker_int(worker):
    worker.log.info("worker received INT or QUIT signal")


    ## get traceback info
    import threading, sys, traceback
    id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
    code = []
    for threadId, stack in sys._current_frames().items():
        code.append("\n# Thread: %s(%d)" % (id2name.get(threadId,""),
            threadId))
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename,
                lineno, name))
            if line:
                code.append("  %s" % (line.strip()))
    worker.log.debug("\n".join(code))

def worker_abort(worker):
    worker.log.info("worker received SIGABRT signal")

工作进程正在同步运行。我希望它们同时运行,因为我在这台服务器上每分钟有很多请求。在研究中我发现我可以使用像eventlet这样的python库,它使用 greenthreads 进行并发。为此,我需要将worker_class更改为eventlet:

worker_class = eventlet

但现在我一无所知。我不知道如何为这个项目实现异步绿色线程。可能这是一个愚蠢的问题,但我真的需要一些帮助。

提前致谢。

2 个答案:

答案 0 :(得分:2)

您已经完成了所需的一切。 public partial class MainWindow : Window { static Dispatcher dispatcher = System.Windows.Application.Current.Dispatcher; public static void ShowTrayNotification(ToolTipIcon icon, string title, string text) { if (dispatcher != null && !dispatcher.CheckAccess()) { dispatcher.Invoke(() => ShowTrayNotification(icon, title, text)); return; } UIHelper.ShowTrayNotification(icon, title, text); } } worker_class = eventlet足以同时运行HTTP请求处理程序。然后,您可以在处理程序中为睡眠或IO提供许多并发请求。

答案 1 :(得分:0)

首先,您需要安装软件包

pip install gunicorn[eventlet]

然后,将worker_class更改为eventlet