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; @Configuration @EnableAsync @Slf4j public class ExecutorConfig { @Bean("taskExecutor") public Executor asyncServiceExecutor() { log.info("---建立線程池---"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //核心線程數 executor.setCorePoolSize(10); //最大線程數 executor.setMaxPoolSize(20); //隊列大小 executor.setQueueCapacity(200); //配置線程池中的線程的名稱前綴 executor.setThreadNamePrefix("async-method-"); /* rejection-policy:當pool已經達到max size的時候,如何處理新任務 線程池對拒絕任務的處理策略:此處採用了CallerRunsPolicy策略, 當線程池沒有處理能力的時候,該策略會直接在execute方法的調用線程中運行被拒絕的任務; 若是執行程序已被關閉,則會丟棄該任務 */ executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //設置線程池關閉的時候等待全部任務都完成再繼續銷燬其餘的Bean executor.setWaitForTasksToCompleteOnShutdown(true); //設置線程池中任務的等待時間,若是超過這個時候尚未銷燬就強制銷燬,以確保應用最後可以被關閉,而不是阻塞住 executor.setAwaitTerminationSeconds(60); //執行初始化 executor.initialize(); return executor; } }
/** * 異步調用測試接口 */ public interface IAsyncService { void testAsyncMethod() throws Exception; } @Service @Slf4j public class AsyncServiceImpl implements IAsyncService { //此處taskExecutor和 config中@bean保持一致 @Async("taskExecutor") @Override public void testAsyncMethod() throws Exception{ log.info("異步方法,走起---"); long start = System.currentTimeMillis(); Thread.sleep(5000); long end = System.currentTimeMillis(); log.info("異步方法,結束:" + (end - start) + "毫秒"); } }
3.測試java
public Result<?> test() { System.out.println("1====================="); System.out.println("2====================="); try { asyncService.testAsyncMethod(); } catch (Exception e) { e.printStackTrace(); } System.out.println("3====================="); System.out.println("4====================="); return Result.ok("測試成功!"); }
控制檯打印以下:spring
備註:異步
若是發現啓動項目報錯:async
解決方案:yml中添加配置ide
spring: main: allow-bean-definition-overriding: true