如何在 Spring Boot 中创建不同的 ThreadPoolTask​​Executor? [英] How to create a different ThreadPoolTaskExecutor in Spring Boot?

查看:52
本文介绍了如何在 Spring Boot 中创建不同的 ThreadPoolTask​​Executor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am now using @EnableAsync and @Async annotation to use multithreaded in Spring Boot. I have service A(fast) and service B(slow).

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

How can I set different pool for them? So when there are lots of calls for B, the application can still handle service A in a different pool from B.

@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 像这样配置它们 -

First of all, you can define your thread pool executor and use them as a configure them as beans like this -

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

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

After that, you can specify your executor on method level like this -

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

这篇关于如何在 Spring Boot 中创建不同的 ThreadPoolTask​​Executor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆