flask - web消息通知中,如何用轮询redis来代替轮询数据库?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-04-27 09:03:46
0
2
1338

我想在自己的flask应用中实现简单的消息通知功能,例如管理员向全体用户发公告,或者想某个用户发出提醒等功能。

可是在实现过程中遇到了一个难题,情况具体描述如下:

我使用sse机制来使服务器向客户端发送消息,可是这里出现了问题,就是发送消息的模块并不知道什么时候应该发送消息,例如当用户A评论了用户B的博客时,这时就需要通知用户B,我们此时需要通知发送模块:“你该向B发送消息了”,如何通知发送模块呢?

我想到的就是轮询数据库,但是感觉这样太考验服务器的抗压了,百度到说:每当对应的数据表更新,就产生一个消息到Redis中,然后轮询Redis。

这样听起来挺好,可是在实现中遇到了很多问题:

例如:(1)redis是key-value存储,当管理员既要给A发消息,又要给B,C等发消息,此时用key该如何区分?

    (2)假设现在要给用户B发消息,那么会产生对应的消息存储在redis中,如果此刻
    用户B并未登录呢,难道用户B一周不登录,该消息就会在redis中一周吗?
    【我对redis不太了解,知道是在缓存中存储,所以感觉不可能在缓存中能存储一周】

思考两三天了,望各位前辈能够指点一二

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(2)
阿神

redis pub/sub subscription/push, have you considered using this or more advanced message queue middleware?

The basic logic is this, the message needs to be cached in the database or other nosql.
Split out the message center and use the redis pub/sub system or list. Others who need to send messages will notify the message center to send messages through redis.
The message center checks whether the user is online, sends messages directly to the user online (via websocket, etc., SSE is also available), and marks it as read.
If the user is online, all unread messages will be pulled. Messages will be stored regardless of whether they are online or not. . . .
Since the value of redis is a string, to distinguish users, you only need the value to be a json string.

{
    "target":["a","b"],
    "message":"我是要发送给用户a和b的消息"
}
phpcn_u1582

key holds the message type
value holds business data, such as the dict after serialization. You can put whatever you want, as much as you want. Then you can take it out and deserialize it and use it directly

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!