About the storage problems of user chats chat system

Question:

Chats can save to redis, because of the chats are time, so I would like to use expired function redis automatically deleted to a certain point in time

 

Reply:

Theoretically possible, but highly not recommended!
For example, I thought I could use the keys of the characteristics redis:
assumptions User_a and User_b sent two messages, you can save it as:

import redis
conn = redis.Redis(host='localhost', port=6379)
# 按照 User_a:User_b:+ 时间戳来设置 key, value 为聊天记录内容
conn.set('User_a:User_b:2018060123050809001', 'msg1')
# 设置过期时间为 3 second
conn.set('User_a:User_b:2018060123050809002', 'msg2', ex=3)

# 通过 Redis.keys 来获取所有`User_a`发送给`User_b`的信息的keys
msg_keys = conn.keys('User_a:User_b:*')

# 通过获得的keys来获取所有信息内容
msgs = conn.mget(msg_keys) if msg_keys else []

But we see is due redis in accordance with key-value pairs to store data, it is not very easy to query data, does not support some of the more complex query conditions, even this solution for the above, there may be performance issues, refer to: redis production environment caution keys fuzzy matching methodkeysthe method can be replaced with scan_itermethods.

In summary, by redis storing chat history is not a very wise choice. Redis not born to do this thing.

I recommend using mongodb be implemented, reference:  Expire Setting the Data from the Collections by TTL . Of course, a relational database can also be achieved in this business need, need to add a  create_time field, then every time the query is not only to detect chats expired, that is to meet create_time + expires > datetime.now()chats.

Published 105 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_38890412/article/details/104079502