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

运行结果:

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

Spring Boot中,可以通过自定义事件来实现在特定情况下触发一些自定义的逻辑或功能。下面是一个演示如何调用自定义事件的例子: 首先,我们需要定义一个自定义事件类,例如`CustomEvent`,该类需要继承`ApplicationEvent`: ```java public class CustomEvent extends ApplicationEvent { private String message; public CustomEvent(Object source, String message) { super(source); this.message = message; } public String getMessage() { return message; } } ``` 然后,我们需要定义一个事件发布者类,例如`CustomEventPublisher`,该类负责发布自定义事件: ```java @Component public class CustomEventPublisher { @Autowired private ApplicationEventPublisher applicationEventPublisher; public void publishCustomEvent(String message) { CustomEvent customEvent = new CustomEvent(this, message); applicationEventPublisher.publishEvent(customEvent); } } ``` 接下来,我们可以在需要的地方注入`CustomEventPublisher`,并调用`publishCustomEvent`方法来发布自定义事件: ```java @Service public class MyService { @Autowired private CustomEventPublisher customEventPublisher; public void doSomething() { // 执行一些业务逻辑 // ... // 发布自定义事件 customEventPublisher.publishCustomEvent("Custom event message"); } } ``` 最后,我们需要定义一个事件监听器类,例如`CustomEventListener`,该类负责监听并处理自定义事件: ```java @Component public class CustomEventListener implements ApplicationListener<CustomEvent> { @Override public void onApplicationEvent(CustomEvent customEvent) { // 处理自定义事件 String message = customEvent.getMessage(); System.out.println("Received custom event with message: " + message); } } ``` 通过以上步骤,我们就可以在Spring Boot中调用自定义事件了。当`MyService`中的`doSomething`方法被调用时,会触发自定义事件发布,然后`CustomEventListener`会监听到该事件并进行处理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Coder-文小白

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

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

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

打赏作者

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

抵扣说明:

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

余额充值