skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. Since you mentioned in your comments, you will have a single chat room, redis lists work for a chat room.

    • The elements will be sorted in insertion order (good for timeline of chat)
    • A single list supports more than 4 billion of elements (probably more than enough)
    • You may use 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.
    • Use LRANGE to paginate messages with 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.
    • If you are going to keep only last n messages(depending on your business rules) in the list then you may use LTRIM.
    • I don’t think you will need a specific message for public chatroom, because 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;

    • LRANGE (first 100 elements): 42123.00 requests per second
    • LRANGE (first 300 elements): 15015.02 requests per second
    • LRANGE (first 450 elements): 10159.50 requests per second
    • LRANGE (first 600 elements): 7548.31 requests per second

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search