2017-09-17 60 views
1

this doc我瞭解到,現在我們可以從任何操作方法返回Callable<T>。彈簧將在TaskExecutor的幫助下,在單獨的線程中執行此操作。 This blog只是說這個TaskExecutor是可配置的。但我沒有找到在spring引導應用程序中配置這個TaskExecutor的方法。誰能幫我?Spring Boot異步請求處理任務執行程序配置

我的另一個問題是我應該擔心這個TaskExecutor的配置,如線程池大小,隊列大小等?

由於pkoli問,這裏是我的主類

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

回答

1

終於找到answer here

要使用其他實現的TaskExecutor的,我們可以從WebMvcConfigurerAdapter擴展我們的配置類,或者我們可以使用它作爲豆。例如,在啓動應用程序:

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

要創建一個任務執行簡單地用適合您需求的配置,如下所示創建一個bean。

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

關於您的問題的第二部分,是的,需要提供配置記住您的應用程序。

下面是來自javadoc的解釋。

當一個新的任務在方法execute(一個java.lang.Runnable)提交,少於corePoolSize線程在運行,創建一個新的線程來處理請求,即使其他輔助線程是空閒的。如果有多於corePoolSize但小於maximumPoolSize線程正在運行,則僅當隊列已滿時纔會創建新線程。

+0

您好,我想這一點,但是這是行不通的。 Spring引導使用另一個執行程序,其線程前綴名稱爲:「MvcAsync1」。我還需要做其他什麼嗎? –

+0

你可以在這裏分享你的配置,這將有助於回答這個問題。看來由Spring提供的默認Task Executor正在被使用,因此線程的前綴爲MvcAsync1。 – pkoli

+0

嘿,我沒有使用任務執行器的任何配置。實際上我的application.properties中沒有任何內容。我只是複製您的代碼並將其粘貼到我的主類中 –