故事是這樣的毙死,就是作品點(diǎn)贊數(shù)试溯,評論數(shù)柜去,轉(zhuǎn)發(fā)量 緩存同步數(shù)據(jù)數(shù)量
原來隊友沒有同步數(shù)據(jù)庫灰嫉,導(dǎo)致排序不生效,現(xiàn)在要我處理
思路1
- 直接在他們調(diào)用的地方 在集成數(shù)據(jù)庫同步的代碼嗓奢,簡單 代碼越來越耦合 讼撒,臃腫不堪 ,每個地方集成
思路2
- 利用spring 事件機(jī)制股耽,沒個集成的地方根盒,發(fā)布事件,觀察者模式其實(shí)就是
思路3
- 提供上下文操作發(fā)布事件方法豺谈,內(nèi)聚起來郑象,其他地方用 只需要 持有上下文對象就行,不需要每個地方再去 發(fā)布事件
代碼演示
- 內(nèi)聚 調(diào)用方法
@Component
public class WorkEventContext {
@Autowired
private ApplicationContext applicationContext;
/**
* 作品 點(diǎn)贊事件
* @param worksId
* @param count
*/
public void publishLikeEvent(Long worksId,Integer count){
WorkLikeEvent workLikeEvent = new WorkLikeEvent();
workLikeEvent.setWorkId(worksId);
workLikeEvent.setLikeCount(count);
applicationContext.publishEvent(workLikeEvent);
}
/**
* 發(fā)布一個評論 事件
* @param workId
* @param count
*/
public void publishDiscussEvent(Long workId,Integer count){
WorkDiscussEvent workDiscussEvent = new WorkDiscussEvent();
workDiscussEvent.setWorkId(workId);
workDiscussEvent.setDiscussCount(count);
applicationContext.publishEvent(workDiscussEvent);
}
/**
* 作品轉(zhuǎn)發(fā) 事件
* @param workId
* @param count
*/
public void publishForwardEvent(Long workId,Integer count){
WorkForwardEvent workForwardEvent = new WorkForwardEvent();
workForwardEvent.setWorkId(workId);
workForwardEvent.setForwardCount(count);
applicationContext.publishEvent(workForwardEvent);
}
}
- 解耦 觀察者
@Component
@Slf4j
public class WorkListener {
@Autowired
private WorksService worksService;
/**
* 點(diǎn)贊
* @param event
*/
@EventListener
public void handleWorkLikeEvent(WorkLikeEvent event) {
Long workId = event.getWorkId();
Integer likeCount = event.getLikeCount();
log.info("作品id:{},作品點(diǎn)贊數(shù):{}",workId,likeCount);
Works works = new Works();
works.setId(workId);
works.setLikeCount(likeCount);
worksService.updateById(works);
}
/**
* 評論
* @param event
*/
@EventListener
public void handleWorkDiscussEvent(WorkDiscussEvent event) {
Long workId = event.getWorkId();
Integer discussCount = event.getDiscussCount();
log.info("作品id:{},作品評論數(shù):{}",workId,discussCount);
Works works = new Works();
works.setId(workId);
works.setDiscussCount(discussCount);
worksService.updateById(works);
}
/**
* 轉(zhuǎn)發(fā)
* @param event
*/
@EventListener
public void handleWorkForwardEvent(WorkForwardEvent event) {
Long workId = event.getWorkId();
Integer forwardCount = event.getForwardCount();
log.info("作品id:{},作品轉(zhuǎn)發(fā)數(shù):{}",workId,forwardCount);
Works works = new Works();
works.setId(workId);
works.setForwardCount(forwardCount);
worksService.updateById(works);
}
}
- 使用