[Spring]如何在项目中应用Spring的事件监听器

前言

本文章只讲实战内容,相关原理请查看我的前两篇文章进行了解。
[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已经失去了意义了。

最后,如果觉得本文章不错,请给我点个赞吧,感激不尽!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,042评论 6 490
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 89,996评论 2 384
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,674评论 0 345
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,340评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,404评论 5 384
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,749评论 1 289
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,902评论 3 405
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,662评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,110评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,451评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,577评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,258评论 4 328
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,848评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,726评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,952评论 1 264
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,271评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,452评论 2 348

推荐阅读更多精彩内容