学习使用spring Event 心得
前言:
近期一直在尝试将业务代码解耦;尝试过mq、考虑过redis,都不能满足目前的场景;最后通过请教同事得知还有这样一种方式(spring Event)可以解耦业务代码;
基本实现方式:
要使用Event只要准备三个部分:
事件类:定义事件,创建一个普通的实体类(构造方法、getter、setter)。
发布者:发布事件,通过ApplicationEventPublisher发布事件。
监听者:监听并处理事件,使用@EventListener或@TransactionalEventListener注解。
直接代码演示:
一、创建推送消息实体(添加 构造方法、getter、setter)
@ApiModel(value = "推送消息实体", description = "推送消息实体")
public class DemoEvent {
@ApiModelProperty(value = "事件id")
private Integer eventId;
private Integer basicId;
private Integer changType;
private Integer oldId;
private String oldValue;
private Integer currentId;
private String currentValue;
private Date runTime;
private String reason;
private Date modifytime;
private Integer modifierid;
}
二、创建事件发送类
/**
* @author :
* @description: 事件发送
* @date : Created in 16:36 2020/9/22
*/
@Slf4j
@Component
public class DemoSendEvent {
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private IHSLListenPeopleChangeRepository ihslListenPeopleChangeRepository;
@Transactional
public void publishEvent() {
Date date = new Date();
HSLListenPeopleChangeEntity listenPeopleChangeEntity =
new HSLListenPeopleChangeEntity(66, 66, 1, 1, "old",
2, "new", date, date, date, 1, 1,
false, "reason");
HSLListenPeopleChangeEntity hslListenPeopleChangeEntity = ihslListenPeopleChangeRepository.save(listenPeopleChangeEntity);
DemoEvent demoEvent = new DemoEvent(66, 66, 2, 43, "原值", 44, "现值", date, "测试测试", date, 55);
publisher.publishEvent(demoEvent);
log.info("发送事件——" + JSON.toJSON(demoEvent));
}
}
三、创建事件监听类
/**
* @author :
* @description: 事件监听
* @date : Created in 16:35 2020/9/22
*/
@Slf4j
@Service
public class DemoEventListener {
@Autowired
private IHSLListenPeopleChangeRepository ihslListenPeopleChangeRepository;
@Transactional(propagation = Propagation.REQUIRES_NEW)
@TransactionalEventListener
public void eventListener(DemoEvent demoEvent) {
log.info("监听者打印监听到的消息" + JSON.toJSON(demoEvent));
Date date = new Date();
HSLListenPeopleChangeEntity listenPeopleChangeEntity =
new HSLListenPeopleChangeEntity(99, 99, 1, 1, "old",
2, "new", date, date, date, 1, 1,
false, "reason");
HSLListenPeopleChangeEntity hslListenPeopleChangeEntity = ihslListenPeopleChangeRepository.save(listenPeopleChangeEntity);
log.info("监听者测试事务" + JSON.toJSON(hslListenPeopleChangeEntity));
}
}
说明:一、发送事件,定义好要发送的内容,调用发送接口(传参是Object的接口);
二、监听事件:
1.不用等监听的对象提交事务就处理,用@EventListener注解
2.需要等监听的对象提交事务才处理,用 @TransactionalEventListener注解
3.由于在监听的方法里还要保存数据库、在监听的方法上还要添加事务注解
@Transactional(propagation = Propagation.REQUIRES_NEW)否则数据不能持久化;