Reputation: 1066
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 ?
Upvotes: 0
Views: 148
Reputation: 1066
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.
Upvotes: 0
Reputation: 9594
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 with linked lists
, both adding a message to the beginning or end of the list is same, O(1), which is great. start
and end
. it wouldn't be beneficial to get all messages at once, you may have possible memory, network related problems, Careful about using LRANGE
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.This is the benchmark for LRANGE from official redis documentation;
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 in userId:time:message
format. both options seems fine.
Upvotes: 1