论坛项目进展05
第5章 Kafka,构建TB级异步消息系统
5.1阻塞队列
注意,解决线程通信的方式不只阻塞队列一种,像wait/notify方法也可以实现,但是太麻烦。
5.2 kafka入门
5.3spring整合kafka
5.4发送系统通知
在entity下建Event
public class Event {
private String topic;//主题,就是事件类型
private int userId;//事件是谁发出的。即事件的触发者
private int entityType;//这个事件发生在哪个实体上,比如帖子,评论
private int entityId;
private int entityUserId;//以及这个实体的作者是谁
private Map<String, Object> data = new HashMap<>();//可能需要一些额外的数据需要记录
public String getTopic() {
return topic;
}
public Event setTopic(String topic) {
this.topic = topic;
return this;
}
public int getUserId() {
return userId;
}
public Event setUserId(int userId) {
this.userId = userId;
return this;
}
public int getEntityType() {
return entityType;
}
public Event setEntityType(int entityType) {
this.entityType = entityType;
return this;
}
public int getEntityId() {
return entityId;
}
public Event setEntityId(int entityId) {
this.entityId = entityId;
return this;
}
public int getEntityUserId() {
return entityUserId;
}
public Event setEntityUserId(int entityUserId) {
this.entityUserId = entityUserId;
return this;
}
public Map<String, Object> getData() {
return data;
}
public Event setData(String key, Object value) {
this.data.put(key, value);
return this;
}
}
新建一个event包,包下面建EventConsumer和EventProducer
修改CommentController:
修改LikeController:
修改FollowController:
5.5显示系统通知
把上一章节存到数据库的系统消息显示在页面上。
在MessageMapper增加:
// 查询某个主题下最新的通知
Message selectLatestNotice(int userId, String topic);
// 查询某个主题所包含的通知数量
int selectNoticeCount(int userId, String topic);
// 查询未读的通知的数量
int selectNoticeUnreadCount(int userId, String topic);
// 查询某个主题所包含的通知列表
List<Message> selectNotices(int userId, String topic, int offset, int limit);
在MessageService增加:
public Message findLatestNotice(int userId, String topic) {
return messageMapper.selectLatestNotice(userId, topic);
}
public int findNoticeCount(int userId, String topic) {
return messageMapper.selectNoticeCount(userId, topic);
}
public int findNoticeUnreadCount(int userId, String topic) {
return messageMapper.selectNoticeUnreadCount(userId, topic);
}
public List<Message> findNotices(int userId, String topic, int offset, int limit) {
return messageMapper.selectNotices(userId, topic, offset, limit);
}
在MessageController增加: