首页 > 解决方案 > Django Channels 停止使用 self.receive_lock.locked 错误

问题描述

我正在努力解决使用 Django Channels 制作通知系统的问题。它在本地运行良好。在生产中(在 Webfaction 上),它可以正常工作几分钟,然后停止工作并出现以下错误消息:

ERROR - server - Exception inside application: 
  File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/sessions.py", line 175, in __call__
    return await self.inner(receive, self.send)
  File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call
await inner_instance(receive, send)
  File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/consumer.py", line 54, in __call__
await await_many_dispatch([receive, self.channel_receive], self.dispatch)
  File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels/utils.py", line 57, in await_many_dispatch
await task
  File "/home/client/.virtualenvs/project/lib/python3.6/site-packages/channels_redis/core.py", line 400, in receive
assert not self.receive_lock.locked()

我在用着:

这都是使用django的开发服务器。

我的消费者看起来像这样:

class NotificationConsumer (AsyncJsonWebsocketConsumer):
    slight_ordering = True

    async def connect (self):
        self.user = self.scope["user"]
        await self.accept()
        group_name = "notifications_{}".format(self.user.employee.pk)
        await self.channel_layer.group_add(group_name, self.channel_name)

    async def disconnect (self, code):
        self.user = self.scope["user"]
        group_name = "notifications_{}".format(self.user.employee.pk)
        await self.channel_layer.group_discard (group_name, self.channel_name)

    async def user_notification (self, event):
        await self.send_json(event)

通知在创建时发送,使用 post_save 信号:

@receiver(post_save, sender=Notification)
def new_notification (sender, instance, **kwargs):
    channel_layer = get_channel_layer()
    group_name = "notifications_{}".format(instance.employee.pk)
    async_to_sync(channel_layer.group_send)(
       group_name, {
           "type": "user.notification",
           "event": "New notification",
           "notification_pk": instance.pk,
       }
    )

我的路由如下所示:

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter(
            [url(r'^notifications/$', NotificationConsumer),]
        )
    ),
})

最后,我在前端使用 WebSocketBridge:

const webSocketBridge = new channels.WebSocketBridge();
webSocketBridge.connect('/notifications/');
webSocketBridge.listen(function(action, stream){
   //show the notification
});

如果有人知道可能发生的事情以及为什么我会收到此 self.receive_lock.locked() 错误,我将不胜感激。

谢谢

标签: pythondjangowebsocketredisdjango-channels

解决方案


这个问题在 channels-redis 版本 2.3.3 中得到修复 将 channels-redis 更新到 2.3.3 如果这引发任何进一步的错误或不支持您的安装,请按照下面的链接更新您的 core.py 文件。虽然不建议编辑包,但这将解决锁定问题。 关联


推荐阅读