如何在 Spring Boot 中创建不同的 ThreadPoolTaskExecutor? [复制]
Posted
技术标签:
【中文标题】如何在 Spring Boot 中创建不同的 ThreadPoolTaskExecutor? [复制]【英文标题】:How to create a different ThreadPoolTaskExecutor in Spring Boot? [duplicate] 【发布时间】:2019-12-16 13:22:22 【问题描述】:我现在使用@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;
【问题讨论】:
也许这对你有帮助:How to use multiple threadPoolExecutor for Async Spring 以下问题也有配置***.com/q/56286235/7458887 【参考方案1】:首先,你可以定义你的线程池执行器并将它们用作配置它们作为这样的bean -
@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;
【讨论】:
这样如何设置AsyncUncaughtExceptionHandler?【参考方案2】:@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");
【讨论】:
以上是关于如何在 Spring Boot 中创建不同的 ThreadPoolTaskExecutor? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
如何从 JSON 数组在 DB 中创建表以在 Spring Boot 中创建 REST API
我如何在 Spring Boot/MVC 中创建错误处理程序(404、500...)