配置异步线程池
package com.sudy.chargerpad.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Nullable
@Override
public Executor getAsyncExecutor() {
//定义线程池
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//核心线程数
taskExecutor.setCorePoolSize(10);
//线程池最大线程数
taskExecutor.setMaxPoolSize(30);
//线程队列最大线程数
taskExecutor.setQueueCapacity(200);
//初始化
taskExecutor.initialize();
return taskExecutor;
}
}
测试service
package com.sudy.chargerpad.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async
public void async(){
System.out.println("线程名称:"+Thread.currentThread().getName());
}
}
测试controller
@Autowired
private AsyncService asyncService;
@GetMapping("/async")
public String async(){
System.out.println("c 线程名称:"+Thread.currentThread().getName());
asyncService.async();
return "async";
}
测试结果控制器方法和service方法使用两个线程
c 线程名称:http-nio-8092-exec-1
线程名称:ThreadPoolTaskExecutor-1