SpringBoot中实现事件的监听,可以方便的实现同步和异步对监听事件进行处理。
1、首先,需要定义监听的事件
import org.springframework.context.ApplicationEvent;
public class MyApplicationEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
EventDto eventDto;
public MyApplicationEvent(Object source, EventDto eventDto) {
super(source);
this.eventDto = eventDto;
}
public EventDto getEventDto() {
return eventDto;
}
public void setEventDto(EventDto eventDto) {
this.eventDto = eventDto;
}
}
2、定义监听器,实现监听器接口的方法,监听器需要加入Spring容器进行管理,可以使用@Component注解,或在入口类中通过context对象添加到容器中。 (这里使用的异步调用,需要在方法onApplicationEvent上添加@Async注解,并在入口类中开启异步请求:@EnableAsync)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Async
public void onApplicationEvent(MyApplicationEvent event) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.info("接收到事件,时间为:" + df.format(new Date()));
}
}
3、在需要的位置将事件发布出去,等待被监听到
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class EventPublisher {
@Autowired
ApplicationContext applicationContext;
public void publish(MyApplicationEvent event) {
applicationContext.publishEvent(event);
}
}
4、注册事件
publisher.publish(new MyApplicationEvent(this, eventDto));