python 在 nginx 和 uwsgi 上的 django 项目 运行 中启动进程需要时间
python process takes time to start in django project running on nginx and uwsgi
我正在使用 python 的多处理模块启动一个进程。该过程由在 django 项目中发送的 post 请求调用。当我使用开发服务器 (python manage.py runserver) 时,post 请求不会花时间启动进程并立即完成。
我使用 nginx 和 uwsgi 将项目部署到生产环境中。
现在,当我发送相同的 post 请求时,大约需要 5-7 分钟才能完成该请求。它只发生在我开始流程的那些 post 请求中。其他 post 请求工作正常。
延迟的原因可能是什么?我该如何解决这个问题?
后台处理基本上需要在WSGI应用模块之外启动。
在 WSGI 中,启动了一个 python webapp 进程来处理请求,请求的数量因配置而异。如果此进程产生一个新进程,它将阻止 WSGI 进程处理新请求,使服务器阻塞并等待它完成,然后再处理新请求。
我建议您使用 WSGI 应用程序模块中的共享队列来馈入在 WSGI 应用程序模块外部 启动的进程。像下面这样的东西。这将为 webapp 模块外的每个 WSGI 进程启动一个新处理器,以免阻塞请求。
your_app/webapp.py
:
from . import bg_queue
def post():
# Webapp POST code here
bg_queue.add(<task data>)
your_app/processor.py
:
from multiprocessing import Process
class Consumer(Process):
def __init__(self, input_q):
self.input_q = input_q
def run(self):
while True:
task_data = input_q.get()
<process data>
your_app/__init__.py
:
from .processor import Consumer
bg_queue = Queue()
consumer = Consumer(bg_queue)
consumer.daemon = True
consumer.start()
我想出了一个解决方法(不知道它是否可以作为答案)。
我将后台进程作为数据库中的作业编写,并使用 cronjob 来检查我是否有任何待处理的作业,如果有任何作业,cron 将为该作业启动后台进程并退出。
cron 将 运行 每分钟执行一次,因此不会有太多延迟。这有助于提高性能,因为它帮助我执行这样繁重的任务 运行 与主应用程序分开。
我正在使用 python 的多处理模块启动一个进程。该过程由在 django 项目中发送的 post 请求调用。当我使用开发服务器 (python manage.py runserver) 时,post 请求不会花时间启动进程并立即完成。
我使用 nginx 和 uwsgi 将项目部署到生产环境中。
现在,当我发送相同的 post 请求时,大约需要 5-7 分钟才能完成该请求。它只发生在我开始流程的那些 post 请求中。其他 post 请求工作正常。
延迟的原因可能是什么?我该如何解决这个问题?
后台处理基本上需要在WSGI应用模块之外启动。
在 WSGI 中,启动了一个 python webapp 进程来处理请求,请求的数量因配置而异。如果此进程产生一个新进程,它将阻止 WSGI 进程处理新请求,使服务器阻塞并等待它完成,然后再处理新请求。
我建议您使用 WSGI 应用程序模块中的共享队列来馈入在 WSGI 应用程序模块外部 启动的进程。像下面这样的东西。这将为 webapp 模块外的每个 WSGI 进程启动一个新处理器,以免阻塞请求。
your_app/webapp.py
:
from . import bg_queue
def post():
# Webapp POST code here
bg_queue.add(<task data>)
your_app/processor.py
:
from multiprocessing import Process
class Consumer(Process):
def __init__(self, input_q):
self.input_q = input_q
def run(self):
while True:
task_data = input_q.get()
<process data>
your_app/__init__.py
:
from .processor import Consumer
bg_queue = Queue()
consumer = Consumer(bg_queue)
consumer.daemon = True
consumer.start()
我想出了一个解决方法(不知道它是否可以作为答案)。 我将后台进程作为数据库中的作业编写,并使用 cronjob 来检查我是否有任何待处理的作业,如果有任何作业,cron 将为该作业启动后台进程并退出。
cron 将 运行 每分钟执行一次,因此不会有太多延迟。这有助于提高性能,因为它帮助我执行这样繁重的任务 运行 与主应用程序分开。