python - python tornado websocket服务器的瓶颈
问题描述
我有一个用 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
解决方案
我主要使用 tornado 来托管我的 webapps,因此我可以告诉你,如果你在 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
装饰器包装它
这个问题和你的类似。答案也很丰富。
推荐阅读
- kubernetes - 从容器运行时的角度来看,pod 和容器有什么区别?
- php - 通过第三方服务器获取的 JWT 登录 Wordpress 站点
- machine-learning - 当我使用参数运行 GridSearchCV() 分类器时,出现这种错误:-ValueError: could not convert string to float: 'text'
- algorithm - 对 dart 中字符串列表中的项目进行排名
- spring - Spring 文档中的何处解释了从 SpEL 表达式中引用 bean?
- flutter - 动画控制器不工作,为什么?
- javascript - 使用自定义管道更改 Datepicker (Angular) 中显示的日期格式
- java - 在 Activity 中将文本从 Fragment 设置为 Navigation Drawer
- java - Springboot中@PreAuthorise的Junit测试用例
- python - 如何通过按下没有硒的按钮重定向到另一个页面?