Python Tornado Web 服务器 : How to use multiprocessing to speed up web application

标签 python web server multiprocessing tornado

我有一个 Web 应用程序,在一个用户使用时运行良好,但随着越来越多的客户开始使用它,它的速度慢得令人无法忍受。服务器端是用python写的,用的是tornado。我注意到虽然它运行的服务器有 4 个内核,但只使用了 1 个,所以我开始研究 python 的多处理。我从以下位置看到了基本示例:http://sebastianraschka.com/Articles/2014_multiprocessing_intro.html和 Tornado 处理器来自: http://tornado.readthedocs.org/en/latest/_modules/tornado/process.html (这似乎有点复杂),但我仍然不确定这就是我要找的东西。当有 50 个用户同时查看时,用 4 个处理器运行这段代码会加快速度吗?如果是这样的话,这些选项之一是使用 Tornado 网络服务器时实现的方式吗?

对于这个模糊且写得不好的问题,我深表歉意 - 即使经过广泛的研究,我也缺乏多处理经验。如果任何示例代码有助于回答这个问题,请告诉我。

谢谢!

最佳答案

您可以使用如下代码运行多个 tornado worker:

import tornado.web
import tornado.httpserver
import tornado.ioloop

class MyHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self):
        self.write('OK')
        self.finish()

if __name__=='__main__':
    app = tornado.web.Application([(r'/', MyHandler)])

    server = tornado.httpserver.HTTPServer(app)
    server.bind(8888)

    server.start(4) # Specify number of subprocesses

    tornado.ioloop.IOLoop.current().start()

尽管您的应用即使在一个内核上也无法为 50 位用户提供服务,这很奇怪。你在那里有一些繁重的计算,或者你是否使用任何阻塞库?

确保在处理程序方法上使用 @tornado.web.asynchronous@tornado.gen.coroutine 装饰器,否则您只是在同步运行代码。

更新:为了在单独的进程中完成繁重的工作,您可以使用 concurrent.futures.ProcessPoolExecutor。看看这个答案:https://stackoverflow.com/a/25208213/1525432 .

关于Python Tornado Web 服务器 : How to use multiprocessing to speed up web application,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32273812/

相关文章:

ssl - 我无法在我的网站中添加Comodo SSl,请您指导我

html - 网站不适合所有屏幕分辨率

python - 如何启用 Azure Web 应用服务的并发请求

python - 如何读取 CSV、创建二维码并将其文件名写入新列?

python - list.__str__ 反转

html - 将 css 文件连接到 godaddy 上的 html

mysql - Symfony 中的数据库连接错误

c - 为什么我的服务器只将文件的第一行写入客户端?

python - "from __future__ imports must occur at the beginning of the file": what defines the beginning of the file?

python - 比较 python 字典列表与列顺序的公差