springboot事件实现,区别于使用消息队列的事件机制
生活中的事件,有触发事件的动作,事件发生了以后有处理事件的机制,事件的类型。带着这样的思路来理解springboot会如何事件。
首先定义事件,以面向对象的思路来理解,那应该是有接口或者是类来标识具备这样的方法的类就是事件类。
springboot使用ApplicationEvent做为事件类的父类。
import org.springframework.context.ApplicationEvent;
public class BusinessTrackEvent extends ApplicationEvent{
/**
* Create a new ApplicationEvent.
*
* @param businessTrackEventEntity the object on which the event initially occurred (never {@code null})
*/
public BusinessTrackEvent(BusinessTrackEventEntity businessTrackEventEntity) {
super(businessTrackEventEntity);
}
}
接下来应该有一个处理事件的类,springboot中使用ApplicationListener接口来定义处理事件的监听类
@Log4j2
@Component
//Application<ApplicationEvent>泛型类型也可以使用BusinessTrackEvent,如果是一个监听方法监听不同类型的事件可以使用ApplicationEvent,如果针对具体某个事件的监听,泛型类型写具体的事件类型
public class CustomsEventListener implements ApplicationListener<ApplicationEvent>{
@Autowired
@Lazy
private MongoTemplate mongoTemplate;
@Autowired
private BusinessTrackMapper businessTrackMapper;
@Autowired
private IAccountManagement accountManagement;
@Async
@Override
@Transactional
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof CustomsEvent){
CustomsEventEntity customsEventEntity=(CustomsEventEntity) event.getSource();
mongoTemplate.insert(customsEventEntity);
}
if(event instanceof BusinessTrackEvent){
BusinessTrackEventEntity businessTrackEventEntity=(BusinessTrackEventEntity) event.getSource();
businessTrackEventEntity.setOperatorUsername(accountManagement.getUserName(businessTrackEventEntity.getOperatorUserId()));
businessTrackMapper.saveBusinessTrack(businessTrackEventEntity);
}
}
}
发布事件,对外提供事件发布机制,使用ApplicationEventPublisher发布事件。
@Component
public final class PublisherCustomsEvent {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publisherEvent(ApplicationEvent applicationEvent){
applicationEventPublisher.publishEvent(applicationEvent);
}
}