JavaEE開發的顛覆者:Spring Boot實戰 學習筆記4--Spring高階話題
阿新 • • 發佈:2018-12-14
SpringAware
可呼叫Spring所提供的資源
多執行緒
配置類
/** * 多執行緒和併發程式設計 */ @Configuration @ComponentScan("com.wisely.highlight_spring4_idea.ch3.taskexecutor") @EnableAsync //開啟非同步任務支援 //實現AsyncConfigurer介面,重寫getAsyncExecutor方法返回一個ThreadPoolTaskExecutor public class TaskExecutorConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() {//獲得基於執行緒池TaskExecutor ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.setMaxPoolSize(10); taskExecutor.setQueueCapacity(25); taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
Service 註解Async
@Service public class AsyncTaskService { @Async //註解宣告這是個非同步方法,若註解在類級別,則表明該類的方法都是非同步方法 //而這裡的方法都自動被注入使用ThreadPoolTaskExecutor作為TaskExecutor public void executeAsyncTask(Integer i){ System.out.println("非同步任務1:"+i); } @Async public void executeAsyncPlus(Integer i){ System.out.println("非同步任務2:"+(i+1)); } }
計劃任務
@EnableScheduling//開啟對計劃任務的支援
@Scheduled(fixedRate = 5000)//計劃任務 每隔5s執行一次