spring 異步任務 開啟線程


一些接口操作可以畢竟費時,而tomact線程的數量又是有限的,想要提高web吞吐量可以在spring里開啟異步。spring默認的線程是有限的(反正默認的不太好之類的),需要自己手工配置個線程池效果會更好。

@Configuration
@EnableAsync//開啟對異步任務的支持
public class ThreadAsyncConfigurer  implements AsyncConfigurer {
  @Bean
  public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
    //設置核心線程數
threadPool.setCorePoolSize(10);
    //設置最大線程數
threadPool.setMaxPoolSize(100);
    //線程池所使用的緩沖隊列
threadPool.setQueueCapacity(10);
    //等待任務在關機時完成--表明等待所有線程執行完
threadPool.setWaitForTasksToCompleteOnShutdown(true);
    // 等待時間 (默認為0,此時立即停止),並沒等待xx秒后強制停止
threadPool.setAwaitTerminationSeconds(60);
    //  線程名稱前綴
threadPool.setThreadNamePrefix("MyAsync-");
    // 初始化線程
threadPool.initialize();
    return threadPool;
  }

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

}

 

 

 
        

使用就很方便 在接口上加上@Async,如果加在類上則表示該類的所有接口都是異步的

 

@Service
public class AsyncTaskService {
  @Async
  public void executeAsyncTask(Integer n){
    System.out.println("異步任務執行:"+n);
  }


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

 


免責聲明!

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



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