SpringBoot 使用 ApplicationEvent

目录

简介

事件监听简述

实例

同步监听(无序)

同步监听(有序)

异步监听(无序)


简介

说明

本文用示例介绍SpringBoot中的事件的用法及原理。

事件监听简述

事件的发布与监听从属于观察者模式;和MQ相比,事件的发布与监听偏向于处理服务内的某些逻辑。 

多个监听器可以监听同一个事件。例如:发布了事件A,监听器A和监听器B都监听了事件A,则监听器A和B都会进行处理。

同步与异步监听

监听方式特点使用时机
同步监听发布器线程与监听器线程处于同一线程1.监听逻辑处理较快
2.需要紧接着根据监听器追踪业务线程
异步监听发布器线程与监听器线程处于不同线程1.监听逻辑处理比较耗时
2.追求响应性能

事件的顺序

可使用实现Ordered接口的方式,调整监听器顺序。

注意:必须是同时实现 ApplicationListener<MyEvent>,Ordered这样的方法才能控制顺序。

下边几种都是无法控制顺序的:

  • @Component+@EventListerner+实现Ordered
  • 实现 ApplicationListener<MyEvent>+@Order

实例

同步监听(无序)

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
 
public class MyEvent extends ApplicationEvent {
 
    public MyEvent(Object source) {
        super(source);
    }
 
}

监听器

监听器1

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener {
    @EventListener
    public void abc(MyEvent event) {
        System.out.println("监听器:        " + "MyListener");
        System.out.println("监听器所在线程:" + Thread.currentThread().getName());
        System.out.println("事件:          " + event);
        System.out.println("事件的数据:    " + event.getSource());
    }
}

监听器2

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener2 {
 
    @EventListener
    public void onApplicationEvent(MyEvent event) {
        System.out.println("监听器:      " + "MyListener2");
        System.out.println("  所在线程:  " + Thread.currentThread().getName());
        System.out.println("  事件:      " + event);
        System.out.println("  事件的数据:" + event.getSource());
    }
}

发布器

package com.example.event;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
 
@Component
public class MyPublisher {
    @Autowired
    ApplicationContext applicationContext;
 
    public void myPublish(String message) {
        System.out.println("发布器所在线程:" + Thread.currentThread().getName());
        applicationContext.publishEvent(new MyEvent(message));
    }
}

测试

写一个Controller

package com.example.controller;
 
import com.example.event.MyPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
    @Autowired
    MyPublisher myPublisher;
 
    @GetMapping("/test1")
    public String test1() {
        myPublisher.myPublish("Hello");
        return "test1 success";
    }
}

启动后,访问:http://localhost:8080/test1

后端输出:

发布器所在线程:http-nio-8080-exec-1
监听器:      MyListener
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
监听器:      MyListener2
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello

可以发现,所有监听器和发布器都在同一个线程

同步监听(有序)

事件

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
 
public class MyEvent extends ApplicationEvent {
 
    public MyEvent(Object source) {
        super(source);
    }
 
}

监听器

监听器1

package com.example.event;
 
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener implements ApplicationListener<MyEvent>,  Ordered {
    @Override
    public void onApplicationEvent(MyEvent event) {
        System.out.println("监听器:      " + "MyListener");
        System.out.println("  所在线程:  " + Thread.currentThread().getName());
        System.out.println("  事件:      " + event);
        System.out.println("  事件的数据:" + event.getSource());
    }
 
    @Override
    public int getOrder() {
        return 2;
    }
}

监听器2

package com.example.event;
 
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener2 implements ApplicationListener<MyEvent>, Ordered {
 
    public void onApplicationEvent(MyEvent event) {
        System.out.println("监听器:      " + "MyListener2");
        System.out.println("  所在线程:  " + Thread.currentThread().getName());
        System.out.println("  事件:      " + event);
        System.out.println("  事件的数据:" + event.getSource());
    }
 
    @Override
    public int getOrder() {
        return 1;
    }
}

发布器

package com.example.event;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
 
@Component
public class MyPublisher {
    @Autowired
    ApplicationContext applicationContext;
 
    public void myPublish(String message) {
        System.out.println("发布器所在线程:" + Thread.currentThread().getName());
        applicationContext.publishEvent(new MyEvent(message));
    }
}

测试

写一个Controller

package com.example.controller;
 
import com.example.event.MyPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
    @Autowired
    MyPublisher myPublisher;
 
    @GetMapping("/test1")
    public String test1() {
        myPublisher.myPublish("Hello");
        return "test1 success";
    }
}

启动后,访问:http://localhost:8080/test1

后端输出:

发布器所在线程:http-nio-8080-exec-1
监听器:      MyListener2
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
监听器:      MyListener
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello

如果将监听器的实现的Ordered顺序颠倒,则输出结果如下:

发布器所在线程:http-nio-8080-exec-1
监听器:      MyListener
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
监听器:      MyListener2
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello

异步监听(无序)

开启异步配置,配置线程池

@Configuration
// 开启spring异步
@EnableAsync  
public class BaseConfig {

    @Bean("XXXXExecutor")
    public ThreadPoolTaskExecutor XXXXExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(50);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(500);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("XXXXExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}

方法:

  • 开启异步监听
  • 在监听器上加@Async(此监听器必须是@Component方法注册的)

事件

package com.example.event;
 
import org.springframework.context.ApplicationEvent;
 
public class MyEvent extends ApplicationEvent {
 
    public MyEvent(Object source) {
        super(source);
    }
 
}

同步监听器

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
 
@Component
public class MyListener {
    @EventListener
    public void abc(MyEvent event) {
        System.out.println("监听器:      " + "MyListener");
        System.out.println("  所在线程:  " + Thread.currentThread().getName());
        System.out.println("  事件:      " + event);
        System.out.println("  事件的数据:" + event.getSource());
    }
}

异步监听器

package com.example.event;
 
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
 
@Component
// 采用默认线程池
//@Async
//采用配置好的XXXXExecutor线程池
@Async("XXXXExecutor")
public class MyListener2 {
 
    @EventListener
    public void onApplicationEvent(MyEvent event) {
        System.out.println("监听器:      " + "MyListener2");
        System.out.println("  所在线程:  " + Thread.currentThread().getName());
        System.out.println("  事件:      " + event);
        System.out.println("  事件的数据:" + event.getSource());
    }
}

发布器

package com.example.event;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
 
@Component
public class MyPublisher {
    @Autowired
    ApplicationContext applicationContext;
 
    public void myPublish(String message) {
        System.out.println("发布器所在线程:" + Thread.currentThread().getName());
        applicationContext.publishEvent(new MyEvent(message));
    }
}

启动类

package com.example;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
 
@SpringBootApplication
@EnableAsync
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

测试

写一个Controller

package com.example.controller;
 
import com.example.event.MyPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
    @Autowired
    MyPublisher myPublisher;
 
    @GetMapping("/test1")
    public String test1() {
        myPublisher.myPublish("Hello");
        return "test1 success";
    }
}

启动后,访问:http://localhost:8080/test1

后端输出:

发布器所在线程:http-nio-8080-exec-1
监听器:      MyListener
  所在线程:  http-nio-8080-exec-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello
监听器:      MyListener2
  所在线程:  task-1
  事件:      com.example.event.MyEvent[source=Hello]
  事件的数据:Hello

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值