Python tornado web server: How to use multiprocessing to speed up web application

心已入冬 提交于 2019-12-04 20:50:55
vitaliy

You can run multiple tornado workers with code like this:

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

Although it's pretty strange that your app have problems serving 50 users even on one core. Do you have some heavy computations there, or do you use any blocking libs?

Make sure you use @tornado.web.asynchronous or @tornado.gen.coroutine decorators on your handler methods, otherwise you are just running your code synchronously.

UPDATE: In order to do the heavy-lifting work in a separate process you can use concurrent.futures.ProcessPoolExecutor. Take a look at this answer: https://stackoverflow.com/a/25208213/1525432.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!