0

我正在尝试使用 django 实时显示访客计数器。比如有多少访问者在我的网站上在线。

我写了一个 websocket 消费者,但即使我在多个浏览器中打开网站,它也总是给我 0。

这是我的 django 频道消费:

class VisitorConsumer(WebsocketConsumer):
    user_count = 0
    def connect(self):
        self.room_name = 'visitors'
        self.room_group_name = 'counter_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

         # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'send_visitor_count',
                'count': self.user_count
            }
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )
       

    # Receive message from room group
    def send_visitor_count(self, event):
        count = event['count']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'count': count
        }))

这是路由:

websocket_urlpatterns = [
    re_path(r'ws/visitors/$', consumers.VisitorConsumer),
]

我不明白为什么它总是触发 0。

任何人都可以帮助解决这个问题吗?

4

1 回答 1

0

我看不到您在哪里增加 user_count,但即使增加它也可能不起作用,因为在不同工作人员中运行的消费者的不同实例将无法访问相同的 user_count 变量。所以你应该把它存储在像 Redis 或 DB 这样的缓存中,不要忘记实际增加它

于 2020-08-28T13:48:39.067 回答