springBoot中定义多个线程池

业务中因为两个项目代码合并,同时使用了异步线程池,为了业务上隔离,决定将两个线程池分离,遂记录。

一、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();
    }
}

五、调用

@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());
    }
}

你可能感兴趣的:(springBoot中定义多个线程池)