I am trying to build a chat room and I want to store additional information like: nickname, time and avatar then associate them to a message.
I might use ‘:’ to separate between some properties but it doesn’t sound like an elegant way!
$list = "message_history";
$message = $data['nickname'] . ':' . $data['message'];
Redis::lpush($list, $message);
Is there an elegant way to do so using Redis ?
2
Answers
I ended up using a hash 'hset'. And by giving each message an id and save them in a separate list I could access all the messages through that list.
Since you mentioned in your comments, you will have a single chat room,
redis lists
work for a chat room.sorted in insertion order
(good for timeline of chat)LPUSH
/RPUSH
to add new message, and since Redis lists are implemented withlinked lists
, both adding a message to the beginning or end of the list is same, O(1), which is great.start
andend
. it wouldn’t be beneficial to get all messages at once, you may have possible memory, network related problems, Careful about usingLRANGE
for large list with high offset from either side.LTRIM
.LINDEX
is O(n) (except first and last). if you are going to need, consider it carefully.Edit:
In your case you may push elements in
username:avatar:time:message format
and parse it when you need to display. You consider to save users in a hash structure, and and save all user related properties in hashes and create messages inuserId:time:message
format. both options seems fine.