How Redis lists may be used to implement a chat sy

2019-07-21 00:15发布

问题:

Here is an example from Redis intro:

$ redis-cli rpush messages "Hello how are you?"
OK
$ redis-cli rpush messages "Fine thanks. I'm having fun with Redis"
OK
$ redis-cli rpush messages "I should look into this NOSQL thing ASAP"
OK
$ redis-cli lrange messages 0 2
1. Hello how are you?
2. Fine thanks. I'm having fun with Redis
3. I should look into this NOSQL thing ASAP

Below they write the following:

As you can guess from the example above, lists could be used in order to implement a chat system.

My question is: what do they really mean saying to implement a chat system?

For example, a message in a chat has at least three parameters:

1) a text of a message,

2) an author of a message,

3) time a message was written.

In the code example above I see only one parameter: a text of a message.

So how lists may be used to implement a chat system? Where do they suppose to store other two parameters and how to connect them to a message in Redis list?

UPD:

I found a great book to understand what Redis is:

http://openmymind.net/2012/1/23/The-Little-Redis-Book/

It is short, simple but very informative.

回答1:

Here are two possibilities:

  • Use a reference. You can put your message in a hash object containing several fields. The key of this hash must be generated from a sequence (incr), or can be a UUID, or any other unique identifier. This key will be the reference to your message, so you just have to push it in the list instead of the text of your message. Up to the receiver to fetch the content of the message once the reference has been popped from the list.

  • Use serialization. Just serialize the various fields of your message using any format you want (example: json, xml, messagepack, etc ...), and push the result to the list. Obviously, the receiver will have to deserialize the item to retrieve the various fields.



标签: nosql redis