Redis实现的评论即时通知服务(redis评论通知)

2023-05-11 09:28:16 评论 通知 即时

Recently, many apps are built with a comment system which make users leave their own opinion on the page. It is generally accepted as an indispensable feature for user interaction. Though comment systems may have different designs, we can break it down into three parts: comment submission, comment broadcasting, and comment notification.

For conventional Rls-based application, an application stack like HTTP + MySQL are usually used. However, response time could become quite slow when a large number of concurrent requests arrive, thus making comment notification worse.

Nowadays, when building such a system, developers are more and more inclining to Redis, a versatile key-value distributed storage with ultra-fast read and write performance, on top of its built-in data structures like list and hash that facilitate application development. Redis as an event sourcing platform can be a perfect fit for comment system.

The comment system we are building is consisted of two parts: backend application and frontend application. On the backend part, Ruby on Rls handles the user data validation, comment creation and update. When a comment is created or updated, an event is triggered and the comment data is saved in Redis. On the frontend part, the comment data from Redis is rendered and updated via AJAX.

In order to implement real-time commenting notification, we can leverage Redis features agn. After a comment is posted, a message is pushed to Redis’ pub/sub channel. Both frontend and backend can subscribe to the channel and notify users accordingly.

Specifically, when a new comment created or updated, a comment event is triggered, and the event data is saved in Redis. Rls model callback makes sure that subscribe to the Redis pub/sub is up and running. Then, the new comment data is sent to the pub channel and the comment data is synchronized on the frontend.

The following is a sample code snippet showing how Redis is used to perform comment notification:

“`ruby

# Server side code

# Model callback that handles user comment creation, update and delete.

# This method will be triggered upon any comment action

class Comment

after_save :notify_comment

def notify_comment

Redis.new.publish(‘comment_channel’, self.comment_data.to_json)

end

end

# Frontend side code

# This method subscribe to ‘comment_channel’ from Redis and

# handle new comment updates accordingly

$(function(){

var con = Redis.connect({ hosting: ‘localhost’ });

con.subscribe(‘comment_channel’,function (err,res){

var coment_data = JSON.parse(res[1]);

// Handle updates and other logic here

});

});


In general, with Redis on board, real-time comment notification could be achieved in an effective and efficient manner. In addition to real-time commenting, Redis can also be used to cache comment data, which greatly reduces the database load and thereby improves system performance.

相关文章