首先,有这样一个异步监听方法
然后配置好了异步线程池
package com.fdw.study.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@ComponentScan(basePackages = {"com.fdw.study.event", "com.fdw.study.eventListener"})
@Configuration
public class EventConfig {
//自定义线程池
@Bean
public ThreadPoolTaskExecutor asyncThreadPoolExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
// 核心线程数
taskExecutor.setCorePoolSize(4);
// 线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程
taskExecutor.setMaxPoolSize(20);
// 缓存队列
taskExecutor.setQueueCapacity(50);
// 空闲时间,当超过了核心线程数之外的线程在空闲时间到达之后会被销毁
taskExecutor.setKeepAliveSeconds(200);
// 异步方法内部线程名称
taskExecutor.setThreadNamePrefix("fdw-async-executor-");
/**
* 当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize,如果还有任务到来就会采取任务拒绝策略
* 通常有以下四种策略:
* ThreadPoolExecutor.AbortPolicy:丢弃任务,抛出RejectedExecutionException异常。
* ThreadPoolExecutor.DiscardPolicy:丢弃任务,但不抛出异常。
* ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试重新执行任务。
* ThreadPoolExecutor.CallerRunsPolicy:重试添加当前的任务,自动重复调用 execute() 方法,直到成功。
*/
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}
执行测试
package com.fdw.study.test;
import com.fdw.study.config.EventConfig;
import com.fdw.study.event.UserChangePasswordEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class EventTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
context.publishEvent(new UserChangePasswordEvent("145623"));
}
}
发现还是走的main线程,没有实现异步
原因:后来发现是配置类缺少了**@EnableAsync**注解,加上后再测试
现在才是真的异步