只需要创建一个 Java 配置类, 实现 AsyncConfigurer 接口, 实现 getAsyncExecutor 方法返回线程池. 在 java 配置文件类上加注解 @EnableAsync 开启异步可用, 然后就可以在 service 方法上使用注解 @Async 使用异步调用
1. 创建一个 java 配置类文件.
package com.codingos.springboot.test.config;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
/**
* 定义线程池
*/
@Override
public Executor getAsyncExecutor() {
// 定义线程池
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
// 设置核心线程
taskExecutor.setCorePoolSize(10);
// 设置最大线程
taskExecutor.setMaxPoolSize(30);
// 设置线程队列最大线程数
taskExecutor.setQueueCapacity(2000);
// 初始化
taskExecutor.initialize();
return taskExecutor;
}
}
2. 创建异步服务 service
package com.codingos.springboot.test.service.impl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.codingos.springboot.test.service.AsyncService;
@Service
public class AsyncServiceImpl implements AsyncService {
@Override
@Async // 声明使用异步调用
public void generateReport() {
// 打印当前异步线程名称
System.out.println("报表线程名称" + Thread.currentThread().getName());
}
}
然后就可以在 controller 中调用了
要注意的是:异步配置文件类上要使用 @EnableAsync 注解,异步 service 的方法上使用 @Async 注解