spring的事件机制实战

理论

在分布式场景下,实现同步转异步的方式有三种方式:
1.异步线程池执行;比如借助@Asyn注解,放到spring自带的线程池中去执行;
2.放到消息队列中,在消费者的代码中异步的消费,执行相关的逻辑;
3.基于spring的事件机制,触发事件,在监听器里实现相关逻辑;

spring中自带了事件的支持,核心类是ApplicationEventPublisher;

事件包括三个要点:下面是一个demo的实现,理论结合实战。

1 事件的定义;

package com.springbootpractice.demoevent.event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEvent;
/**
* @说明 吃饭事件
* @作者 carter
* @创建时间 2019年07月12日 13:12
**/
public class EatEvent extends ApplicationEvent {
private static final Logger logger = LoggerFactory.getLogger(EatEvent.class);
private Boolean eatFinished;
public EatEvent(Boolean eatFinished) {
super(eatFinished);
this.eatFinished = eatFinished;
}
public void callGirlFriend() {
logger.info("美女,吃完饭了,来收拾一下吧!");
}
public void callBrothers() {
logger.info("兄弟们,吃完饭了,来打dota !");
}
public Boolean getEatFinished() {
return eatFinished;
}
}

2 事件监听的定义;

package com.springbootpractice.demoevent.event.listener;
import com.springbootpractice.demoevent.event.EatEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.util.Objects;
/**
* 说明: XEvent的事件监听器
*
* @author carter
* 创建时间 2019年07月12日 13:19
**/
@Component
public class EatEventListener implements ApplicationListener<EatEvent> {
private static final Logger logger = LoggerFactory.getLogger(EatEventListener.class);
@Override
public void onApplicationEvent(EatEvent xEvent) {
if (Objects.isNull(xEvent)) {
return;
}
if (xEvent.getEatFinished()) {
xEvent.callGirlFriend();
logger.info("xxxx,女朋友拒绝收拾!");
xEvent.callBrothers();
logger.info("满人了,下次带你!");
}
}
}

3 发布事件;

package com.springbootpractice.demoevent.web;
import com.springbootpractice.demoevent.event.EatEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 说明 测试控制器
*
* @author carter
* 创建时间 2019年07月12日 13:23
**/
@RestController
public class TestController {
private final ApplicationEventPublisher applicationEventPublisher;
@Autowired
public TestController(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
@GetMapping(path = "/eatOver")
public Object eatOver() {
EatEvent xEvent = new EatEvent(true);
applicationEventPublisher.publishEvent(xEvent);
return "eat over and publish event success";
}
}

无需多余的配置,springmvc直接支持的;

实战

完整代码地址

posted @   李福春  阅读(601)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示