场景
设计一个评论系统,有如下功能:
- 发表评论
- 删除评论
- 查看评论 为了方便讨论问题,我们可以用今日头条文章下面的评论区作为例子
QPS 存储
存储
-
Context Table 评论区表 用于存储评论区信息,比如是哪篇文章的评论区 | column | notes | | --------- | ----------- | | id | primary key | | article_id | 关联的文章/博客 |
-
Commnet Table 评论表
| column | notes |
|---|---|
| id | primary key |
| ctx_id | 评论区id |
| content | 评论内容 |
| user_id | 用户id |
| reply_to | 评论id(非回复该字段为null) |
| is_deleted | 是否删除 |
发布评论
insert into comment_table xxxxx
查看评论区评论
select * from comment_table where ctx_id = xx and reply_to is null
删除评论
update comment_table set is_deleted = 1 where id =
写入与读取
我们可以将数据写入到mysql,将数据同步到ES,再从ES进行读取。
数据同步到ES有多种方式:
- 在往comment表写入一条数据之后,发送一条kafka消息,消费消息将数据写入到ES中
- 监听mysql的binlog变更,将数据写入到ES中
数据在写入到mysql后,我们就可以向客户端返回写入成功,数据从mysql同步到ES异步进行。
扩展
如何实现点赞与点踩
为了防止一个人多次点赞,我们可以新增一张表,用于存储点赞相关信息
- Reaction Table | column | notes | | --------- | ----------- | | id | primary key | | comment_id | 评论id | | user_id | 用户id | | reaction | 1-up 2-down |
在读取点赞数的时候,可以从数据库进行count,考虑到点赞数的实时性和准确性要求不高,我们可以考虑将数据缓存在redis,在有新的点赞动作时,更新缓存的数据。