SpringBoot中使用监听器

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";
    }
}
相关推荐
侠客行031717 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪17 小时前
深入浅出LangChain4J
java·langchain·llm
Victor35617 小时前
https://editor.csdn.net/md/?articleId=139321571&spm=1011.2415.3001.9698
后端
Victor35617 小时前
Hibernate(89)如何在压力测试中使用Hibernate?
后端
灰子学技术19 小时前
go response.Body.close()导致连接异常处理
开发语言·后端·golang
老毛肚19 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
风流倜傥唐伯虎19 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
Yvonne爱编码20 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚20 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂20 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言