SpringBoot事件发布监听

一、好处

模块解耦、异步、消息广播、触发某一事件

二、实现

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);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值