前言
本文章只讲实战内容,相关原理请查看我的前两篇文章进行了解。
[Spring]详解Spring中的事件监听器模式
[设计模式]事件监听器模式
实现interface应用事件监听器模式
- SimpleApplicationEvent: 定义事件
package com.tea.modules.bean.applicationevent;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.context.ApplicationEvent;
/**
* @author jaymin
* 2021/1/16 23:50
*/
@Builder
public class SimpleApplicationEvent extends ApplicationEvent {
/**
* 事件内容
*/
@Getter
@Setter
private String message;
public SimpleApplicationEvent(String message) {
super(message);
this.message = message;
}
}
- SimpleApplicationListenerA: 定义事件监听器A
package com.tea.modules.bean.applicationevent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @author jaymin
* 2021/1/16 23:52
*/
@Component
@Slf4j
public class SimpleApplicationListenerA implements ApplicationListener<SimpleApplicationEvent> {
/**
* 监听事件进行处理
*
* @param event 事件对象
*/
@Override
public void onApplicationEvent(SimpleApplicationEvent event) {
log.info("SimpleApplicationListenerA receive event :{} ", event.getMessage());
}
}
- SimpleApplicationListenerB: 定义事件监听器B
package com.tea.modules.bean.applicationevent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @author jaymin
* 2021/1/17 0:07
*/
@Component
@Slf4j
public class SimpleApplicationListenerB implements ApplicationListener<SimpleApplicationEvent> {
/**
* 监听事件进行处理
*
* @param event 事件对象
*/
@Override
public void onApplicationEvent(SimpleApplicationEvent event) {
log.info("SimpleApplicationListenerB receive event :{} ", event.getMessage());
}
}
- SimpleApplicationPublisher: 定义事件发布者
package com.tea.modules.bean.applicationevent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
/**
* @author jaymin
* 2021/1/17 0:08
*/
@Component
public class SimpleApplicationPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
/**
* 发布事件
* @param event 事件对象
*/
public void publish(SimpleApplicationEvent event) {
applicationEventPublisher.publishEvent(event);
}
}
- Demo
package com.tea.modules.bean.applicationevent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
/**
* @author jaymin
* 2021/1/17 0:11
*/
@ComponentScan("com.tea")
@Slf4j
public class SimpleApplicationEventDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext(SimpleApplicationEventDemo.class);
SimpleApplicationPublisher publisher = annotationConfigApplicationContext.getBean(SimpleApplicationPublisher.class);
SimpleApplicationEvent event = SimpleApplicationEvent.builder().message("Hello,World").build();
publisher.publish(event);
}
}
- Result:
00:42:48.308 [main] INFO com.tea.modules.bean.applicationevent.SimpleApplicationListenerA - SimpleApplicationListenerA receive event :Hello,World
00:42:48.310 [main] INFO com.tea.modules.bean.applicationevent.SimpleApplicationListenerB - SimpleApplicationListenerB receive event :Hello,World
使用@Order声明事件消费顺序
注意,使用接口的方式,@Order需要标记在类上,而不是方法上.
- 声明SimpleApplicationListenerA消费事件的顺序为2
@Component
@Slf4j
@Order(2)
public class SimpleApplicationListenerA implements ApplicationListener<SimpleApplicationEvent>
- 声明SimpleApplicationListenerB消费事件的顺序为2
@Component
@Slf4j
@Order(1)
public class SimpleApplicationListenerB implements ApplicationListener<SimpleApplicationEvent>
- Result:
00:54:57.172 [main] INFO com.tea.modules.bean.applicationevent.SimpleApplicationListenerB - SimpleApplicationListenerB receive event :Hello,World
00:54:57.174 [main] INFO com.tea.modules.bean.applicationevent.SimpleApplicationListenerA - SimpleApplicationListenerA receive event :Hello,World
配合@Async来支持异步消费
在SimpleApplicationListenerA上标记@Async即可.但是仅仅如此并不能支持异步,我们还需要一些线程池的配置.
- SimpleApplicationListenerA
package com.tea.modules.bean.applicationevent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author jaymin
* 2021/1/16 23:52
*/
@Component
@Slf4j
@Order(2)
public class SimpleApplicationListenerA implements ApplicationListener<SimpleApplicationEvent> {
/**
* 监听事件进行处理
*
* @param event 事件对象
*/
@Override
@Async
public void onApplicationEvent(SimpleApplicationEvent event) {
log.info("SimpleApplicationListenerA receive event :{} ", event.getMessage());
}
}
自动化配置自定义线程池
- SpringThreadPoolPropertyConfig: 使用动态化配置线程池参数
package com.tea.spring.threalpool;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* @author jaymin
* 2021/1/17 1:05
*/
@Configuration
@Getter
public class SpringThreadPoolPropertyConfig {
@Value("${thread.pool.core-size:20}")
private Integer corePoolSize;
@Value("${thread.pool.max-size:50}")
private Integer maxPoolSize;
@Value("${thread.pool.keep-alive-seconds:10}")
private Integer keepAliveSeconds;
@Value("${thread.pool.queue-capacity:1000}")
private Integer queueCapacity;
@Value("${thread.pool.await-termination-seconds:0}")
private Integer awaitTerminationSeconds;
@Value("${thread.pool.thread-name-prefix2:spring-tea}")
private String threadNamePrefix;
@Value("${thread.pool.wait-for-tasks-to-complete-on-shutdown:true}")
private Boolean waitForTasksToCompleteOnShutdown;
}
- SpringThreadPoolConfig: 配置TaskExecutor.
package com.tea.spring.threalpool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author jaymin
* 2021/1/17 1:01
*/
@Configuration
@EnableAsync
public class SpringThreadPoolConfig {
@Autowired
private SpringThreadPoolPropertyConfig threadPoolConfig;
@Bean("taskExecutor")
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor customizeThreadPoolTaskExecutor = new ThreadPoolTaskExecutor();
customizeThreadPoolTaskExecutor.setCorePoolSize(threadPoolConfig.getCorePoolSize());
customizeThreadPoolTaskExecutor.setMaxPoolSize(threadPoolConfig.getMaxPoolSize());
customizeThreadPoolTaskExecutor.setKeepAliveSeconds(threadPoolConfig.getKeepAliveSeconds());
customizeThreadPoolTaskExecutor.setQueueCapacity(threadPoolConfig.getQueueCapacity());
customizeThreadPoolTaskExecutor.setAwaitTerminationSeconds(threadPoolConfig.getAwaitTerminationSeconds());
customizeThreadPoolTaskExecutor.setThreadNamePrefix(threadPoolConfig.getThreadNamePrefix());
customizeThreadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(threadPoolConfig.getWaitForTasksToCompleteOnShutdown());
customizeThreadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return customizeThreadPoolTaskExecutor;
}
}
- Test: 这里就不能简单地用main方法启动了,我们需要在SpringBoot环境下去测试.
package com.tea.bean.eventListener;
import com.tea.modules.bean.applicationevent.SimpleApplicationEvent;
import com.tea.modules.bean.applicationevent.SimpleApplicationPublisher;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author jaymin
* 2021/1/17 1:13
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class SimpleApplicationEventTest {
@Autowired
private SimpleApplicationPublisher simpleApplicationPublisher;
@Test
public void testSimpleApplication(){
SimpleApplicationEvent event = SimpleApplicationEvent.builder().message("Hello,World").build();
simpleApplicationPublisher.publish(event);
}
}
- Result:
2021-01-17 01:19:45.855 INFO 9876 --- [ main] c.t.m.b.a.SimpleApplicationListenerB : SimpleApplicationListenerB receive event :Hello,World
2021-01-17 01:19:45.858 INFO 9876 --- [ spring-tea1] c.t.m.b.a.SimpleApplicationListenerA : SimpleApplicationListenerA receive event :Hello,World
可以看到,此时打印的线程为spring-tea1.说明异步调用成功了!
注解形式应用事件监听机制.
- SimpleApplicationEventListenerOfAnnotation
package com.tea.modules.bean.applicationevent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author jaymin
* 2021/1/17 1:28
*/
@Component
@Slf4j
public class SimpleApplicationEventListenerOfAnnotation {
@EventListener()
public void onApplicationEventA(SimpleApplicationEvent event) {
log.info("SimpleApplicationEventListenerOfAnnotation#onApplicationEventA receive event :{} ", event.getMessage());
}
@EventListener()
public void onApplicationEventB(SimpleApplicationEvent event) {
log.info("SimpleApplicationEventListenerOfAnnotation#onApplicationEventB receive event :{} ", event.getMessage());
}
}
- Result: 测试用例不用改,这里直接给出输出的结果.
2021-01-17 01:30:15.405 INFO 4912 --- [ main] mpleApplicationEventListenerOfAnnotation : SimpleApplicationEventListenerOfAnnotation#onApplicationEventB receive event :Hello,World
2021-01-17 01:30:15.405 INFO 4912 --- [ main] mpleApplicationEventListenerOfAnnotation : SimpleApplicationEventListenerOfAnnotation#onApplicationEventA receive event :Hello,World
使用@Order声明消费顺序.
- SimpleApplicationEventListenerOfAnnotation
package com.tea.modules.bean.applicationevent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author jaymin
* 2021/1/17 1:28
*/
@Component
@Slf4j
public class SimpleApplicationEventListenerOfAnnotation {
@EventListener()
@Order(2)
public void onApplicationEventA(SimpleApplicationEvent event) {
log.info("SimpleApplicationEventListenerOfAnnotation#onApplicationEventA receive event :{} ", event.getMessage());
}
@EventListener()
@Order(1)
public void onApplicationEventB(SimpleApplicationEvent event) {
log.info("SimpleApplicationEventListenerOfAnnotation#onApplicationEventB receive event :{} ", event.getMessage());
}
}
- Result
2021-01-17 01:33:31.676 INFO 11836 --- [ main] c.t.m.b.a.SimpleApplicationListenerB : SimpleApplicationListenerB receive event :Hello,World
2021-01-17 01:33:31.676 INFO 11836 --- [ main] mpleApplicationEventListenerOfAnnotation : SimpleApplicationEventListenerOfAnnotation#onApplicationEventB receive event :Hello,World
使用@Async支持异步
此处同样需要沿用上面接口的配置类进行线程池注册.
- SimpleApplicationEventListenerOfAnnotation
package com.tea.modules.bean.applicationevent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author jaymin
* 2021/1/17 1:28
*/
@Component
@Slf4j
public class SimpleApplicationEventListenerOfAnnotation {
@EventListener()
@Order(2)
@Async
public void onApplicationEventA(SimpleApplicationEvent event) {
log.info("SimpleApplicationEventListenerOfAnnotation#onApplicationEventA receive event :{} ", event.getMessage());
}
@EventListener()
@Order(1)
@Async
public void onApplicationEventB(SimpleApplicationEvent event) {
log.info("SimpleApplicationEventListenerOfAnnotation#onApplicationEventB receive event :{} ", event.getMessage());
}
}
- Result:
2021-01-17 01:36:56.664 INFO 7892 --- [ spring-tea3] mpleApplicationEventListenerOfAnnotation : SimpleApplicationEventListenerOfAnnotation#onApplicationEventA receive event :Hello,World
2021-01-17 01:36:56.664 INFO 7892 --- [ spring-tea1] mpleApplicationEventListenerOfAnnotation : SimpleApplicationEventListenerOfAnnotation#onApplicationEventB receive event :Hello,World
可见,在异步的情况下,@Order已经失去了意义了。
最后,如果觉得本文章不错,请给我点个赞吧,感激不尽!