Spring Boot异步请求处理任务执行器配置 [英] Spring Boot Asynchronous Request Processing Task Executor Configuration

查看:33
本文介绍了Spring Boot异步请求处理任务执行器配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 这个文档 我了解到,现在我们可以从任何操作方法返回 Callable.spring 将在 TaskExecutor 的帮助下在单独的线程中执行此操作.这个blog 只说这个 TaskExecutor 是可配置的.但是我没有找到在 spring boot 应用程序中配置这个 TaskExecutor 的方法.任何人都可以帮助我吗?

From this doc I have learned that, now we can return Callable<T> from any action method. And spring will execute this action in a separate thread with the help of a TaskExecutor. This blog only says that this TaskExecutor is configurable. But I did not find a way to configure this TaskExecutor in spring boot application. Can anyone help me?

我的另一个问题是我是否应该担心这个 TaskExecutor 的配置,比如线程池大小、队列大小等?

My another question is should I worry about the configuration of this TaskExecutor like threadpool size, queue size etc?

正如 pkoli 所问,这是我的主类

As pkoli asked, here is my Main class

@SpringBootApplication
public class MyWebApiApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(MyWebApiApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyWebApiApplication.class);
    }

    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("MyThread-");
        executor.initialize();
        return executor;
    }
}

推荐答案

终于找到在这里回答

要使用 TaskExecutor 的其他实现,我们可以从 WebMvcConfigurerAdapter 扩展我们的配置类,也可以将其用作 bean.例如在启动应用程序中:

To use other implementation of TaskExecutor we can extend our configuration class from WebMvcConfigurerAdapter or we can use it as bean. For example in a boot application:

@SpringBootApplication
public class AsyncConfigExample{
    @Bean
    WebMvcConfigurer configurer(){
        return new WebMvcConfigurerAdapter(){
            @Override
            public void configureAsyncSupport (AsyncSupportConfigurer configurer) {
                ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
                t.setCorePoolSize(10);
                t.setMaxPoolSize(100);
                t.setQueueCapacity(50);
                t.setAllowCoreThreadTimeOut(true);
                t.setKeepAliveSeconds(120);
                t.initialize();
                configurer.setTaskExecutor(t);
            }
        };
    }
    public static void main (String[] args) {
        SpringApplication.run(AsyncConfigExample.class, args);
    }
}

这篇关于Spring Boot异步请求处理任务执行器配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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