一、好处
模块解耦、异步、消息广播、触发某一事件
二、实现
1.要监听的事件
import org.springframework.context.ApplicationEvent;
/**
* @author :cxp
* @description :要监听的事件
* @date :2022/8/1 16:09
*/
public class TestEvent extends ApplicationEvent {
private static final long serialVersionUID = -2866878925912581424L;
public TestEvent(Object source) {
super(source);
}
}
2.事件发布
import cn.hutool.core.util.StrUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author :cxp
* @description :发布者
* @date :2022/8/1 16:11
*/
@Component
public class TestPublisher {
@Resource
private ApplicationContext applicationContext;
public void publishEvent(String message) {
if (StrUtil.isNotBlank(message)) {
System.out.println("发布器所在线程:" + Thread.currentThread().getName());
applicationContext.publishEvent(new TestEvent(message));
}
}
}
3.订阅者
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* @author :cxp
* @description :监听者1
* @date :2022/8/1 16:10
*/
@Component
public class TestListener1 {
@EventListener
public void listen1(TestEvent testEvent) {
System.out.println("TestListener1");
System.out.println("所在线程:" + Thread.currentThread().getName());
System.out.println("事件:" + testEvent);
System.out.println("事件的数据:" + testEvent.getSource());
}
}
*****************************************************************************************
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author :cxp
* @description :监听者2(异步执行,*项目中记得加@EnableAsync注解)
* @date :2022/8/1 16:10
*/
@Component
@Async("asyncExecutor")
public class TestListener2 {
// 支持SPEL表达式
@EventListener
public void listen1(TestEvent testEvent) {
System.out.println("TestListener2");
System.out.println("所在线程:" + Thread.currentThread().getName());
System.out.println("事件:" + testEvent);
System.out.println("事件的数据:" + testEvent.getSource());
}
}
4.触发事件
@Slf4j
@RestController
@RequestMapping("/event")
public class TestController {
@Resource
private TestPublisher testPublisher;
@GetMapping("/testEvent")
public ResultData testEvent(String message) {
log.info("[message]={}", message);
testPublisher.publishEvent(message);
return ResultData.success(message);
}
}