天天看點

Springboot使用線程池demo

1、添加application.yml,設定資料

async:
  executor:
    ##核心線程數
    corePoolSize: 10
    ##最大線程數
    maxPoolSize: 10
    ##線程池中的線程的名稱字首
    prefix: async-
    ##隊列大小
    queueCapacity: 10000           

複制

1、配置線程池配置類

建立一個線程池的配置,讓Spring Boot加載,使用

@Configuration

和@

EnableAsync

這兩個注解,表示這是線程池配置類

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
​
@Configuration
@EnableAsync
public class AsyncPoolConfig {
​
    private static final Logger logger = LoggerFactory.getLogger(AsyncPoolConfig.class);
​
   @Value("${async.executor.corePoolSize}")
    private int corePoolSize;
    @Value("${async.executor.maxPoolSize}")
    private int maxPoolSize;
    @Value("${async.executor.queueCapacity}")
    private int queueCapacity;
    @Value("${async.executor.prefix}")
    private String prefix;
​
    @Bean(name = "asyncServiceAsyncPool")
    public Executor asyncServiceAsyncPool() {
        logger.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心線程數
        executor.setCorePoolSize(corePoolSize);
        //配置最大線程數
        executor.setMaxPoolSize(maxPoolSize);
        //配置隊列大小
        executor.setQueueCapacity(queueCapacity);
        //配置線程池中的線程的名稱字首
        executor.setThreadNamePrefix(prefix);
        
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //執行初始化
        executor.initialize();
        return executor;
    }
}           

複制

2、建立異步調用接口以及實作類

public interface AsyncService {
    /**
     * 執行異步任務
     * 可以根據需求測試
     */
    void executeAsync();
}           

複制

實作類

@Service
public class AsyncServiceImpl implements AsyncService {
    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Override
    @Async("asyncServiceAsyncPool")
    public void executeAsync() {
        logger.info("start executeAsync");

        System.out.println("異步線程要做的事情");
        logger.info("end executeAsync");
    }
}           

複制

@Async(“asyncServiceExecutor”)表示指定使用asyncServiceExecutor線程池異步執行該方法,就是@Bean裡邊定義的名稱

3、調用異步方法測試

建立Controller通過注解

@Autowired

注入這個Service

@Autowired
private AsyncService asyncService;

@GetMapping("/async")
public void async(){
    asyncService.executeAsync();
}           

複制