如何在 Spring Boot 中创建不同的 ThreadPoolTask​​Executor?

How to create a different ThreadPoolTaskExecutor in Spring Boot?

我现在使用 @EnableAsync@Async 注释在 Spring Boot 中使用多线程。我有服务 A(快)和服务 B(慢)。

如何为他们设置不同的池?因此,当对 B 有很多调用时,应用程序仍然可以在与 B 不同的池中处理服务 A。

@Configuration
@EnableAsync
public class ServiceExecutorConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(30);
        taskExecutor.setMaxPoolSize(40);
        taskExecutor.setQueueCapacity(10);
        taskExecutor.initialize();
        return taskExecutor;

    }
}
@Bean(name = "threadPoolExecutor")
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(7);
    executor.setMaxPoolSize(42);
    executor.setQueueCapacity(11);
    executor.setThreadNamePrefix("threadPoolExecutor-");
    executor.initialize();
    return executor;
}

@Bean(name = "ConcurrentTaskExecutor")
public TaskExecutor taskExecutor2 () {
    return new ConcurrentTaskExecutor(
            Executors.newFixedThreadPool(3));
}

@Override
@Async("threadPoolExecutor")
public void createUserWithThreadPoolExecutor(){
    System.out.println("Currently Executing thread name - " + Thread.currentThread().getName());
    System.out.println("User created with thread pool executor");
}

@Override
@Async("ConcurrentTaskExecutor")
public void createUserWithConcurrentExecutor(){
    System.out.println("Currently Executing thread name - " + Thread.currentThread().getName());
    System.out.println("User created with concurrent task executor");
}

首先,您可以定义您的线程池执行器并将它们用作像这样将它们配置为 beans -

@Configuration
public class ThreadConfig {
    @Bean
    public TaskExecutor executorA() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(4);
        executor.setThreadNamePrefix("default_task_executor_thread");
        executor.initialize();
        return executor;
    } 

    @Bean
    public TaskExecutor executorB() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(4);
        executor.setThreadNamePrefix("executor-B");
        executor.initialize();
        return executor;
    }
}  

之后,您可以像这样在方法级别指定执行程序 -

@Async("executorA")
public void methodWithVoidReturnType(String s) {
    .....
}

@Async("executorA")
public Future<String> methodWithSomeReturnType() { 
   ...
   try {
      Thread.sleep(5000);
       return new AsyncResult<String>("hello world !!!!");
   } catch (InterruptedException e) {
      ...
   }

   return null;
}