Spring高级 事件监听器 (二)利用线程池异步发送事件

publishEvent 底层调用了一个SimpleApplicationEventMulticaster 来发布事件,属性有一个Executor 可以用来设置异步的方式

一、设置线程池

package com.mangoubiubiu.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class Config {
    @Bean
    public ThreadPoolTaskExecutor executor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);//核心线程数
        executor.setMaxPoolSize(10);//最大线程数
        executor.setQueueCapacity(100);//队列大小
        return  executor;
    }

    @Bean
    public SimpleApplicationEventMulticaster applicationEventMulticaster(ThreadPoolTaskExecutor executor){
        SimpleApplicationEventMulticaster multicaste = new SimpleApplicationEventMulticaster();
         multicaste.setTaskExecutor(executor);
         return multicaste;
    }
}

二 、发布事件后测试

有2个线程来发布事件

posted @ 2022-06-11 16:49  KwFruit  阅读(455)  评论(0编辑  收藏  举报