Spring任務執行器(TaskExecutor)


Spring任務執行器(TaskExecutor)
    Spring通州任務執行器(TaskExecutor)來實現多線程和並發編程,使用ThreadPoolTaskExecutor
可實現一個基於線程的TaskExecutor,而實際開發中任務一般是非阻塞的,即異步的,所以我們要在配置類中
通過@EnableAsync開啟對異步任務的支持,並通過在實際執行的Bean的方法中使用@Async注解來聲明其是一個異步任務。

實例

1.配置類

package com.wisely.highlight_spring4.ch3.taskexecutor;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch3.taskexecutor")
@EnableAsync //1
public class TaskExecutorConfig implements AsyncConfigurer{//2

@Override
public Executor getAsyncExecutor() {//2
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}



代碼解釋
1.利用@EnableAsync注解開啟異步任務支持。
2.配置類實現AsyncConfigurer接口並重寫getAsyncExecutor方法,並返回一個ThreadPoolTaskExecutor,這樣我們就獲得了已個基於線程池TaskExecutor.

任務執行類
package com.wisely.highlight_spring4.ch3.taskexecutor;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {

@Async //1
public void executeAsyncTask(Integer i){
System.out.println("執行異步任務 "+i);
}

@Async
public void executeAsyncTaskPlus(Integer i){
System.out.println("執行異步任務+1"+(i+1));
}
}



代碼解釋
1.通過@Async注解表明該方法是個異步方法,如果注解在類級別,則表明該類所以的方法都是異步的,
而這里的方法自動被注入使用ThreadPoolTaskExecutor作為TaskExecutor。

運行
package com.wisely.highlight_spring4.ch3.taskexecutor;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(TaskExecutorConfig.class);

AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);

for(int i =0 ;i<10;i++){
asyncTaskService.executeAsyncTask(i);
asyncTaskService.executeAsyncTaskPlus(i);
}
context.close();
}
}



結果是並發執行而不是順序執行的。
 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM