springboot使用异步线程池
原文出处 https://www.cnblogs.com/fulongyuanjushi/p/15856660.html
记录一下自己对异步线程池的使用,全部都是参考的原文。
1.定义线程池配置类,自定义线程池
import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; /** * 类名称:ExecutorConfig * ******************************** * <p> * 类描述:线程池配置 * * @author guoj * @date 2021-09-07 09:00 */ @Configuration @EnableAsync @Slf4j public class ExecutorConfig { /** * 定义线程池 * * @return */ @Bean("noticeExecutor") public Executor noticeExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程数量:当前机器的核心数 executor.setCorePoolSize( Runtime.getRuntime().availableProcessors()); // 最大线程数 executor.setMaxPoolSize( Runtime.getRuntime().availableProcessors() * 2); // 队列大小 executor.setQueueCapacity(Integer.MAX_VALUE); // 线程池中的线程名前缀 executor.setThreadNamePrefix("sjsb-"); // 拒绝策略:直接拒绝 executor.setRejectedExecutionHandler( new ThreadPoolExecutor.AbortPolicy()); // 执行初始化 executor.initialize(); return executor; } }
2.编写异步服务
@Slf4j @Service public class AsyncService { /** * 异步请求路由下发回调 * */ @Async("noticeExecutor") public void notice(String str) { // log.info("[异步线程] ========进入方法"); //todo // log.info("[异步线程] ========执行完毕"); } }
3.代码中的使用
@Autowired
AsyncService asyncService;
asyncService.notice("hello");
标签:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通