0
点赞
收藏
分享

微信扫一扫

SpringBoot:@Async如何自定义线程池以及使用教程

🍁 作者:知识浅谈,CSDN签约讲师,CSDN博客专家,华为云云享专家,阿里云专家博主 📌 擅长领域:全栈工程师、爬虫、ACM算法 💒 公众号:知识浅谈 🔥 微信:zsqtcyl 联系我领取福利

看别的教程一大堆废话,直接上干货不行吗,直接看下边例子 想看视频详细讲解的来这:视频讲解点我

🎈引入依赖

<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秒后打印出来。 在这里插入图片描述

🍚总结

大功告成,撒花致谢🎆🎇🌟,关注我不迷路,带你起飞带你富。 Writted By 知识浅谈

举报

相关推荐

0 条评论