springBoot中定義多個線程池

業(yè)務(wù)中因為兩個項目代碼合并,同時使用了異步線程池,為了業(yè)務(wù)上隔離,決定將兩個線程池分離,遂記錄。

一、application.yml

# 線程池配置
primary:
  async:
    corePoolSize: 20
    maxPoolSize: 40
    keepAliveSeconds: 120
    queueCapacity: 100
secondary:
  async:
    corePoolSize: 20
    maxPoolSize: 40
    keepAliveSeconds: 120
    queueCapacity: 100

二、定義封裝實體類

@Data
public abstract class AsyncConstants {
    private int corePoolSize;
    private int maxPoolSize;
    private int keepAliveSeconds;
    private int queueCapacity;
}
@Configuration
@ConfigurationProperties(prefix = "primary.async")
public class PrimaryAsyncConstants extends AsyncConstants {
}
@Configuration
@ConfigurationProperties(prefix = "secondary.async")
public class SecondaryAsyncConstants extends AsyncConstants{
}

三、定義AsyncConfig

@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig {
    private final PrimaryAsyncConstants primaryAsyncConstants;
    private final SecondaryAsyncConstants secondaryAsyncConstants;
    @Autowired
    public AsyncConfig(PrimaryAsyncConstants primaryAsyncConstants, SecondaryAsyncConstants secondaryAsyncConstants) {
        this.primaryAsyncConstants = primaryAsyncConstants;
        this.secondaryAsyncConstants = secondaryAsyncConstants;
    }
    @Bean(name = "primaryExecutor")
    public AsyncTaskExecutor getPrimaryExecutor() {
        return initExecutor(primaryAsyncConstants, "PrimaryExecutor-");
    }
    @Bean(name = "secondaryExecutor")
    public AsyncTaskExecutor getSecondaryExecutor() {
        return initExecutor(secondaryAsyncConstants, "SecondaryExecutor-");
    }
    private ThreadPoolTaskExecutor initExecutor(AsyncConstants constants, String prefix) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(constants.getCorePoolSize());
        executor.setMaxPoolSize(constants.getMaxPoolSize());
        executor.setKeepAliveSeconds(constants.getKeepAliveSeconds());
        executor.setQueueCapacity(constants.getQueueCapacity());
        executor.setThreadNamePrefix(prefix);
        return executor;
    }
}

四、捕捉異常

@Configuration
public class AppConfig implements AsyncConfigurer {
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
        return new CustomAsyncExceptionHandler();
    }
}

五、調(diào)用

@Service
public class AsyncTestServiceImpl implements AsyncTestService {
    @Override
    @Async("primaryExecutor")
    public void testPrimary() {
        System.out.println(Thread.currentThread().getName());
    }
    @Override
    @Async("secondaryExecutor")
    public void secondary() {
        System.out.println(Thread.currentThread().getName());
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容