spring boot 使用TaskExecutor實現非同步任務
阿新 • • 發佈:2019-02-02
1.新增配置類,開啟非同步任務支援
@Configuration //宣告配置類 @EnableAsync //開啟非同步任務支援 public class TaskExecutorConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5);//執行緒池大小 taskExecutor.setMaxPoolSize(10);//執行緒池最大執行緒數 taskExecutor.setQueueCapacity(25);//最大等待任務數 taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
2.通過@Async註解宣告非同步任務
@Service("asyncTaskService") public class AsyncTaskService{ @Async public void excuteAsyncTaskTest(String name) { for(int i = 0;i < 100;i++) { System.out.println("正在執行非同步任務"+name+i); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }