Django频道访客计数器实时



我正试图用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。

有人能帮忙解决这个问题吗?

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

最新更新