看别的教程一大堆废话,直接上干货不行吗,直接看下边例子
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@EnableAsync
@Configuration
public class AsyncConfiguration {
//定义线程池
@Bean("threadPool1") // bean的名称,线程池的bean的名字,不是创建线程的名字
public Executor ThreadPool1(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); /** 核心线程数(默认线程数) */
executor.setMaxPoolSize(20);/** 最大线程数 */
executor.setQueueCapacity(500);/** 缓冲队列大小 */
executor.setKeepAliveSeconds(60);/** 允许线程空闲时间(单位:默认为秒) */
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setThreadNamePrefix("task-thread-"); /** 线程池名前缀 */
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); //拒绝策略:缓存队列满了直接抛弃任务
executor.initialize();
return executor;
}
}
@RestController("/test")
public class Test2Controller {
@Async("threadPool1")
public void test1() throws InterruptedException {
Thread.sleep(5000);
System.out.println("test1");
}
}
@Api("测试")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController
{
@Autowired
private Test2Controller test2Controller;
@ApiOperation("异步")
@GetMapping("/testAsync")
public String testAsync() throws InterruptedException {
test2Controller.test1();
return "async";
}
}
结果: 结果直接返回:test1 5秒后打印出来。
大功告成,撒花致谢🎆🎇🌟,关注我不迷路,带你起飞带你富。