- application.yml
# 异步线程配置 async: executor: thread: # 配置核心线程数 core_pool_size: 5 # 配置最大线程数 max_pool_size: 5 # 配置队列大小 queue_capacity: 99999 # 配置线程池中的线程的名称前缀 name: prefix: async-hahashujia-service-
- AsyncTask.java
package com.hahashujia.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; import java.util.concurrent.Future; /** * @author hahashujia * @description * @date 2019/5/8 0008 17:01 */ @Component public class AsyncTask { private static final Logger logger = LoggerFactory.getLogger(AsyncTask.class); @Async public Future<String> doTask1() throws InterruptedException{ logger.info("Task1 started."); long start = System.currentTimeMillis(); Thread.sleep(5000); long end = System.currentTimeMillis(); logger.info("Task1 finished, time elapsed: {} ms.", end-start); return new AsyncResult<>("Task1 accomplished!"); } @Async public Future<String> doTask2() throws InterruptedException{ logger.info("Task2 started."); long start = System.currentTimeMillis(); Thread.sleep(3000); long end = System.currentTimeMillis(); logger.info("Task2 finished, time elapsed: {} ms.", end-start); return new AsyncResult<>("Task2 accomplished!"); } }
- ExecutorConfig.java
package com.hahashujia.config; import org.springframework.beans.factory.annotation.Value; 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; /** * @author hahashujia * @description * @date 2019/10/24 */ @Configuration @EnableAsync public class ExecutorConfig { @Value("${async.executor.thread.core_pool_size}") private int corePoolSize; @Value("${async.executor.thread.max_pool_size}") private int maxPoolSize; @Value("${async.executor.thread.queue_capacity}") private int queueCapacity; @Value("${async.executor.thread.name.prefix}") private String namePrefix; @Bean(name = "asyncServiceExecutor") public Executor asyncServiceExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //配置核心线程数 executor.setCorePoolSize(corePoolSize); //配置最大线程数 executor.setMaxPoolSize(maxPoolSize); //配置队列大小 executor.setQueueCapacity(queueCapacity); //配置线程池中的线程的名称前缀 executor.setThreadNamePrefix(namePrefix); // rejection-policy:当pool已经达到max size的时候,如何处理新任务 // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //执行初始化 executor.initialize(); return executor; } }
- 线程调用NoticeService.java
package com.hahashujia.service.notice; import lombok.extern.log4j.Log4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; /** * @author hahashujia * @description * @date 2019/5/9 */ @Service @Log4j public class NoticeService { /** * 小明回家吃饭了 * * @return */ @Async("asyncServiceExecutor") public void notice() throws InterruptedException { Thread.sleep(5000); log.info("小明该回家吃饭了"); Thread.sleep(5000); log.info("小明不吃饭就没饭吃了"); Thread.sleep(5000); log.info("饭只剩一半了"); Thread.sleep(5000); log.info("饭吃完了,你可以不用回来了"); } }
- Controller调用:
package com.hahashujia.controller.notice; import com.hahashujia.basic.annotation.ApiType; import com.hahashujia.config.Swagger2Config; import com.hahashujia.service.NoticeService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 异步线程调用 * * @author hahashujia */ @ApiType(apiTypeValue = Swagger2Config.BusinessGroup.BANK_STATEMENT) @Api(description = "异步线程调用") @RestController @RequestMapping("/notice") @Slf4j public class NoticeController { @Autowired private NoticeService noticeService; @GetMapping("/dinner") @ApiOperation(value = "吃饭", notes = "吃饭") public String dinner() throws InterruptedException { noticeService.notice(); log.info("通知已下达"); return "ok"; } }
- 控制台打印结果如下:
SpringBoot——集成异步线程(Executor)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.