spring boot2.x 自定义事件的发布与监听

一、前言

需要实现spring boot自定义事件的发布与监听,其实并没有多复杂,可以分以下三步进行:

  1. 通过继承抽象类ApplicationEvent,自定义事件;
  2. 通过实现 ApplicationListener接口 或者通过 @EventListener 注解到方法上,自定义一个事件的监听;
  3. 通过ApplicationContext对象,发布事件。

二、代码实现

  1. 创建一个spring boot项目,项目结构如下:

在这里插入图片描述
2. 导入maven依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
  1. 自定义一个事件类,继承ApplicationEvent抽象类:
/**
 * 自定义一个事件
 */
@Getter
public class MyEvent extends ApplicationEvent {
    String name;

    public MyEvent(Object source, String name) {
        super(source);
        this.name = name;
    }
}
  1. 自定义一个事件的监听类,实现ApplicationListener接口,并且将监听类注册到spring容器中:
/**
 * 定义一个自定义事件的监听
 */
@Component
@Slf4j
public class MyListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent event) {
        log.info(new StringBuilder()
                .append(event.getName())
                .append("在")
                .append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .append("访问了系统!")
                .toString());
    }
}
  1. 测试,为了方便,创建一个TestController进行测试:
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    // 注入ApplicationContext对象
    @Autowired
    ApplicationContext applicationContext;

    @GetMapping("login")
    public String loginTest(String name) {
        // 发布事件
        applicationContext.publishEvent(new MyEvent(this, name));
        // 日志记录
        log.info(new StringBuilder()
                .append(name)
                .append("在")
                .append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .append("登录成功!")
                .toString());
        // 返回结果
        return name + " login success!";
    }

}

运行项目,访问http://localhost:8080/test/login?name=张三,运行结果:

在这里插入图片描述
可以看到发布的事件成功被监听到了。

@EventListener注解的使用

上面实现监听类的方式是实现ApplicationListener接口,除此之外还可以在方法上使用@EventListener注解,重新实现MyListener ,代码如下:

@Component
@Slf4j
public class MyListener {

    @EventListener
    public void handlerMyEvent(MyEvent event) {
        log.info(new StringBuilder()
                .append(event.getName())
                .append("在")
                .append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .append("访问了系统!")
                .toString());
    }
}

再次访问,运行结果:

在这里插入图片描述
可以看到,结果都可以成功监听到发布的事件。

异步进行事件监听

可以看到,就上面的例子来说,通知张三访问了系统和张三成功登录是没有串联关系的,这个通知事件可以异步进行。

  1. 启动类上添加@EnableAsync注解,开启异步调用:
@SpringBootApplication
@EnableAsync
public class SpringbootEventApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootEventApplication.class, args);
    }

}
  1. 在监听方法上添加@Async注解:
@Component
@Slf4j
public class MyListener {

    @EventListener
    @Async // 异步执行
    public void handlerMyEvent(MyEvent event) {
        log.info(new StringBuilder()
                .append(event.getName())
                .append("在")
                .append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                .append("访问了系统!")
                .toString());
    }
}

运行结果:

在这里插入图片描述
可以看到发布的事件是用另外的线程异步执行的。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码探险家_cool

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值