【问题标题】:bottleneck in python tornado websocket serverpython tornado websocket服务器的瓶颈
【发布时间】:2018-07-03 07:08:39
【问题描述】:

我有一个用 python tornado 编写的 websocket 服务器。服务器将接收来自客户端的许多连接,如您所知,我们有on_message 函数,当接收到 websocket 消息时会触发该函数。所以,这是我的问题,如果一条消息(比如来自客户端的请求)需要 5 秒来处理,那么当服务器正在处理一些请求时,服务器会进入阻塞模式并且不能接受或接收更多的连接或数据。经过一些研究,我发现Asyncio 可以解决我的问题,但我现在不知道如何使用它。那么,如何调用process 方法以避免阻塞?

以下是我的代码:

class WavesClient(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True
    def open(self):
        print("New client connected")

   def on_message(self, message):
        self.process(message)

   def on_close(self):
        print("Client disconnected")
   def process(self,message):
        #it takes 5 sec to complete

【问题讨论】:

标签: python asynchronous websocket tornado


【解决方案1】:

我主要使用 tornado 来托管我的 web 应用程序,因此我可以告诉你,如果你的代码在 tornado 中的任何部分阻塞,整个服务器都会阻塞。

现在到你的代码:

@tornado.gen.coroutine
def on_message(self, message):
    process_results = yield self.process(message)
    self.write_message(process_results)

@tornado.gen.coroutine
def process(self, message):
    # a long process, this is the equivalent of time.sleep(2) which is blocking
    yield tornado.gen.sleep(2)
    return 'finished'

使用tornado,您必须从函数中yield 才能获得返回值。 此外,如果您的函数正在生成,则必须使用 tornado.gen.coroutine 装饰器包装它

question 与您的相似。答案也很丰富。

【讨论】:

  • 但是,如果我想使用函数而不是 tornado.gen.sleep(2),例如 mysql 查询,我刚刚测试了一个非异步函数,它被阻塞了。我只希望应用程序服务器在处理客户端请求时响应其他客户端
  • 在tornado中,强烈建议你编写异步函数,否则会阻塞。对于mysql,使用an async driver to peform queries,示例见链接。
猜你喜欢
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多