Springboot的非同步線程池

來源:互聯網
上載者:User

標籤:而不是   value   could not   capacity   調用   sys   time   應用   min   

1:定義線程池

@EnableAsync    @Configuration    class TaskPoolConfig {        @Bean("taskExecutor")        public Executor taskExecutor() {            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();            executor.setCorePoolSize(10);            executor.setMaxPoolSize(20);            executor.setQueueCapacity(200);            executor.setKeepAliveSeconds(60);            executor.setThreadNamePrefix("taskExecutor-");            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
         executor.setWaitForTasksToCompleteOnShutdown( true );           executor.setAwaitTerminationSeconds( 60 );
            return executor;        }    }

上面我們通過使用ThreadPoolTaskExecutor建立了一個線程池,同時設定了以下這些參數:

  • 核心線程數10:線程池建立時候初始化的線程數
  • 最大線程數20:線程池最大的線程數,只有在緩衝隊列滿了之後才會申請超過核心線程數的線程
  • 緩衝隊列200:用來緩衝執行任務的隊列
  • 允許線程的空閑時間60秒:當超過了核心線程出之外的線程在空閑時間到達之後會被銷毀
  • 線程池名的首碼:設定好了之後可以方便我們定位處理任務所在的線程池
  • 線程池對拒絕任務的處理策略:這裡採用了CallerRunsPolicy策略,當線程池沒有處理能力的時候,該策略會直接在 execute 方法的調用線程中運行被拒絕的任務;如果執行程式已關閉,則會丟棄該任務

說明:setWaitForTasksToCompleteOnShutdown(true)該方法就是這裡的關鍵,用來設定線程池關閉的時候等待所有任務都完成再繼續銷毀其他的Bean,這樣這些非同步任務的銷毀就會先於Redis線程池的銷毀。同時,這裡還設定了setAwaitTerminationSeconds(60),該方法用來設定線程池中任務的等待時間,如果超過這個時候還沒有銷毀就強制銷毀,以確保應用最後能夠被關閉,而不是阻塞住。

 

2:如何使用該線程池呢?

@Slf4j@Componentpublic class Task {    public static Random random = new Random();
    @Autowired      private StringRedisTemplate stringRedisTemplate;
    @Async("taskExecutor")    public void doTaskOne() throws Exception {        log.info("開始做任務一");        long start = System.currentTimeMillis();        Thread.sleep(random.nextInt(10000));        long end = System.currentTimeMillis();
log.info(stringRedisTemplate.randomKey()); log.info("完成任務一,耗時:" + (end - start) + "毫秒"); } @Async("taskExecutor") public void doTaskTwo() throws Exception { log.info("開始做任務二"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("完成任務二,耗時:" + (end - start) + "毫秒"); } @Async("taskExecutor") public void doTaskThree() throws Exception { log.info("開始做任務三"); long start = System.currentTimeMillis(); Thread.sleep(random.nextInt(10000)); long end = System.currentTimeMillis(); log.info("完成任務三,耗時:" + (end - start) + "毫秒"); }}

  

3 執行非同步任務

@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTestpublic class ApplicationTests {    @Autowired    private Task task;    @Test    public void test() throws Exception {        task.doTaskOne();        task.doTaskTwo();        task.doTaskThree();        Thread.currentThread().join();    }}
2018-03-27 22:01:15.620  INFO 73703 --- [ taskExecutor-1] com.didispace.async.Task                 : 開始做任務一2018-03-27 22:01:15.620  INFO 73703 --- [ taskExecutor-2] com.didispace.async.Task                 : 開始做任務二2018-03-27 22:01:15.620  INFO 73703 --- [ taskExecutor-3] com.didispace.async.Task                 : 開始做任務三2018-03-27 22:01:18.165  INFO 73703 --- [ taskExecutor-2] com.didispace.async.Task                 : 完成任務二,耗時:2545毫秒2018-03-27 22:01:22.149  INFO 73703 --- [ taskExecutor-3] com.didispace.async.Task                 : 完成任務三,耗時:6529毫秒2018-03-27 22:01:23.912  INFO 73703 --- [ taskExecutor-1] com.didispace.async.Task                 : 完成任務一,耗時:8292毫秒

  

4 注意事項

從異常信息JedisConnectionException: Could not get a resource from the pool來看,我們很容易的可以想到,在應用關閉的時候非同步任務還在執行,由於Redis串連池先銷毀了,導致非同步任務中要訪問Redis的操作就報了上面的錯。所以,我們得出結論,上面的實現方式在應用關閉的時候是不優雅的,那麼我們要怎麼做呢?如下設定:

executor.setWaitForTasksToCompleteOnShutdown( true ); executor.setAwaitTerminationSeconds( 60 );

 

Springboot的非同步線程池

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.