Spring Boot 线程池实现的关键代码
2018-02-05 11:01
447 查看
启动类申明@EnableAsync
实现AsyncConfigurer
方法上申明 @Async
使用方法
实现AsyncConfigurer
方法上申明 @Async
使用方法
启动类申明@EnableAsync
@SpringBootApplication @EnableAsync public classApplication { public static void main(String[] args){ SpringApplication.run(Application.class); } }
实现AsyncConfigurer
@Configuration @ComponentScan("...") public class AsyncConfiguration implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor tp = new ThreadPoolTaskExecutor(); tp.setCorePoolSize(5); tp.setMaxPoolSize(10); //线程空闲超过这个时间,就回收该线程↓ tp.setKeepAliveSeconds(3000); //队列长度↓ tp.setQueueCapacity(1000); tp.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); tp.initialize(); return tp; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { //异常处理↓ return null; } }
方法上申明 @Async
@Component public class AsyncTest { @Async public void testVoid(String s) { //无返回值 } @Async public Future<String> testFuture(String S){ //有返回值 return new AsyncResult<String> (s); } }
使用方法
@Controller @RequestMapping("/") public class TestControllers { //在需要的地方注入↓ @Autowired private AsyncTest asyncTest; @GetMapping public ModelAndView index(){ asyncTest.testVoid("..."); asyncTest.testFuture("..."); return new ModelAndView("index", "...", "..."); } }
相关文章推荐
- SpringBoot添加自定义拦截器的实现代码
- 详解spring boot实现多数据源代码实战
- Spring Boot/VUE中路由传递参数的实现代码
- 通过Spring Boot配置动态数据源访问多个数据库的实现代码
- spring boot整合spring-kafka实现发送接收消息实例代码
- Angular+Bootstrap+Spring Boot实现分页功能实例代码
- SpringBoot入门-12(springboot配置servlet,利用代码实现)
- Spring Boot实现邮件注册功能示例代码
- Spring Boot使用@Async实现异步调用:自定义线程池
- springboot - 集成mysql实现方式之一,DruidDataSource 完整代码实现
- springboot - 集成redis完整代码实现
- Spring Boot+AngularJS+BootStrap实现进度条示例代码
- spring boot整合Shiro实现单点登录的示例代码
- SpringBoot整合SpringKafka实现生产者史上最简代码实现
- SpringBoot 整合 dubbo xml实现代码示例
- springboot+Quartz实现任务调度的示例代码
- Spring Boot实现跨域访问实现代码
- SpringBoot中发送QQ邮件功能的实现代码
- Springboot集成Kafka实现producer和consumer的示例代码
- springboot - 集成kafka完整代码实现