1.定义一个事件
/**
* 定义事件
* @author hrui
* @date 2024/7/25 12:46
*/
public class CustomEvent extends ApplicationEvent {
private String message;
public CustomEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
在监听器中可以通过 event.getSource(); 来获取事件源
2.通过ApplicationEventPublisher 发布事件
@Service
public class EventPublisherService {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishEvent(String message) {
CustomEvent event = new CustomEvent(this, message);
applicationEventPublisher.publishEvent(event);
}
}
3.通过监听器订阅事件
/**
* 监听事件,订阅事件
* @author hrui
* @date 2024/7/25 12:49
*/
@Component
public class CustomEventListener {
@Async
//@EventListener
//@TransactionalEventListener 有事务的监听
@EventListener(condition = "#event.message == 'hello'") //SPEL(Spring表达式)条件监听 对象也可以用== 判断
//@EventListener(condition = "#event.message .equals('hello') ")
//@EventListener(condition = "#event.message.endsWith("123") ") //很多方法可以选择
public void handleCustomEvent(CustomEvent event) {
System.out.println(Thread.currentThread().getName());
System.out.println("Received event - " + event.getMessage());
}
}
第三步简单实用了@EventListener注解 如果不用就需要这么做
去实现ApplicationListerner<处理的事件> 需不需要异步自己看着办
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class CustomEventListener implements ApplicationListener<CustomEvent> {
@Override
public void onApplicationEvent(CustomEvent event) {
// 条件判断
if ("hello".equals(event.getMessage())) {
// 异步处理
new Thread(() -> {
System.out.println(Thread.currentThread().getName());
System.out.println("Received event - " + event.getMessage());
}).start();
}
}
}
/**
* @author hrui
* @date 2024/7/25 12:51
*/
@RestController
public class ListenerController {
@Autowired
private EventPublisherService eventPublisherService;
@GetMapping("/listener")
public String listener(String message)
{
eventPublisherService.publishEvent(message);
return "listener";
}
}