1. 程式人生 > >springboot中非同步執行緒呼叫問題

springboot中非同步執行緒呼叫問題

1.原始執行緒總結

我們在使用多執行緒的時候,往往需要建立Thread類,或者實現Runnable介面,如果要使用到執行緒池,我們還需要來建立Executors。

2.spring執行緒

只要要@EnableAsync就可以使用多執行緒。使用@Async就可以定義一個執行緒任務。通過spring給我們提供的ThreadPoolTaskExecutor就可以使用執行緒池。

3.使用

3.1 新建springboot專案

3.2 專案匯入idea

目錄結構如下:

3.3 新建執行緒配置類

package com.hotpot.comm.config;

import java.util.concurrent.Executor;
  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.ComponentScan;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.scheduling.annotation.EnableAsync;  
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;  


/**
 * 描述:
 * @author: myx
 * @date: 2018/1/31 0031
 * Copyright © 2017-ganinfo. All rights reserved.
 */
@Configuration  
@ComponentScan("com.hotpot.*.service.impl")
@EnableAsync
public class ThreadConfig  {  
     /**
      * 執行需要依賴執行緒池,這裡就來配置一個執行緒池
      * @return
      */
     @Bean  
     public Executor getExecutor() {  
          ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  
          executor.setCorePoolSize(10);
          executor.setMaxPoolSize(100);
          executor.setQueueCapacity(250);
          executor.initialize();  
          return executor;  
     }  
}  

3.4 新建service類

package com.hotpot.test.service.impl;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;

/**
 * 描述:
 * @author: myx
 * @date: 2018/1/31 0031 17:09
 * @version: V1.0
 * Copyright © 2018-ganinfo. All rights reserved.
 */
@Service
public class TestServiceImpl {
    /**
     * 這裡進行標註為非同步任務,在執行此方法的時候,會單獨開啟執行緒來執行
     */
    @Async
    public void function1() {
        System.out.println("f1 : " + Thread.currentThread().getName() + "   " + UUID.randomUUID().toString());
        try {
            Thread.sleep(new Random().nextInt(100));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async
    public void function2() {
        System.out.println("f2 : " + Thread.currentThread().getName() + "   " + UUID.randomUUID().toString());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3.5 編寫controler

package com.hotpot.test.controller;

import com.hotpot.test.service.impl.TestServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 描述:
 *
 * @author: ruikanwang
 * @date: 2018/1/31 0031 17:24
 * @version: V1.0
 * 注意:本內容僅限於新疆感知科技有限公司內部傳閱,禁止外洩以及用於其他的商業目
 * Copyright © 2018-ganinfo. All rights reserved.
 */
@RestController
public class TestController {
    @Autowired
    TestServiceImpl service;

    @GetMapping("/test")
    public void test(){
        for (int i = 0; i < 10; i++) {
            service.function1(); // 執行非同步任務
            service.function2();
        }
    }
}

3.6 啟動專案

啟動成功訪問http://localhost:8080/test 執行結果:

可以看到非同步呼叫實現成功

4.其他實現方式

package com.hotpot.comm.config;

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.hotpot.*.service.impl")
@EnableAsync  
public class ThreadConfig implements AsyncConfigurer {  
  
     @Override  
     public Executor getAsyncExecutor() {  
          ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  
          executor.setCorePoolSize(5);  
          executor.setMaxPoolSize(10);  
          executor.setQueueCapacity(25);  
          executor.initialize();  
          return executor;  
     }  
  
     @Override  
     public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {  
          return null;  
     }  
  
}  

參考連結: http://blog.csdn.net/king_kgh/article/details/76022136

後續新增springboot 非同步執行緒池starter(實現自定義多個執行緒池共存)請關注部落格

更多知識參見[持續更新]