项目场景:
Django Channels的channels-layer配置redis遇到连接问题:

Django Channels 配置了channels-layer为redis,用以实现群聊。在MacOS开发环境下一切正常,部署到服务器上后客户端始终连接不到ws服务。


问题描述

websocket连接刚刚连上就断开

前端控制台显示,连接成功,秒断,显示连接错误:
反复尝试均不能正常连接。
windows的django、django-channels、channels-redis均重新安装
依旧不能保持正常连接。
重启,redis服务正常。
依旧不能保持正常连接。


原因分析:

结论:windows安装的redis版本太低

先后更改了channels-layer配置下的ip,试了外网访问ip、localhost、局域网ip、主机域名均不能正常连接。客户端返回的提示信息是,刚刚连接上,即断开了连接。在consumers里增加了多个位置的print。后来发现确实是卡在了channels-layer配置这里。

from channels.generic.websocket import AsyncJsonWebsocketConsumer
from channels.exceptions import StopConsumer


class GroupConsumer(AsyncJsonWebsocketConsumer):

    def __init__(self, *args, **kwargs):
        super().__init__(args, kwargs)
        self.group = 'default'

    async def connect(self):
        print('ws连接,当前self.scope', self.scope)
        print('ws连接,当前self.channel_name', self.channel_name)
        self.group = 'group_{}'.format(self.scope['url_route']['kwargs']['group'])
        print('ws连接,当前self.group', self.group)
        # Join room group
        await self.channel_layer.group_add(self.group, self.channel_name)
        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        print('连接断开', close_code)
        await self.channel_layer.group_discard(self.group, self.channel_name)
        raise StopConsumer()

    # Receive message from WebSocket
    async def receive_json(self, content, **kwargs):
        # Send message to room group
        await self.channel_layer.group_send(self.group, {'type': 'message', 'message': content})

    # Receive message from room group
    async def message(self, event):
        # print(event)
        message = event['message']
        # Send message to WebSocket
        await self.send_json(message)

检查了channels、channels-redis是否安装成功。
也检查了windows的redis是否安装且服务已启动。
最后发现是redis版本的问题。


解决方案:

安装高于5.0版本的windows的redis