Task Execution and Scheduling In SpringBoot

開天闢地

In the absence of an Executor bean in the context, Spring Boot auto-configures a ThreadPoolTaskExecutor with sensible defaults that can be automatically associated to asynchronous task execution (@EnableAsync) and Spring MVC asynchronous request processing.

在上下文中沒有Executor bean的情況下,Spring Boot會自動配置一個ThreadPoolTaskExecutor,其中包含合理的默認值,可以自動關聯到異步任務執行(@EnableAsync)和Spring MVC異步請求處理。

By default, Spring uses a SimpleAsyncTaskExecutor to actually run these methods asynchronously. But we can override the defaults at two levels: the application level or the individual method level.

Spring使用SimpleAsyncTaskExecutor來實際以異步方式運行這些方法。但是我們可以在兩個級別上覆蓋默認設置:應用程序級別或單個方法級別。

在@EnableAsync的javadoc中也有相關的一段話作爲關聯佐證:

By default, Spring will be searching for an associated thread pool definition: either a unique org.springframework.core.task.TaskExecutor bean in the context, or an java.util.concurrent.Executor bean named "taskExecutor" otherwise. If neither of the two is resolvable, a org.springframework.core.task.SimpleAsyncTaskExecutor will be used to process async method invocations. Besides, annotated methods having a void return type cannot transmit any exception back to the caller. By default, such uncaught exceptions are only logged.

要麼是上下文中唯一的 org.springframework.core.task.TaskExecutor bean,要麼是名爲 "taskExecutor" 的 java.util.concurrent.Executor bean。如果這兩者都無法解析,則會使用 org.springframework.core.task.SimpleAsyncTaskExecutor 來處理異步方法調用。此外,具有 void 返回類型的註釋方法無法將任何異常傳遞迴調用者。默認情況下,這樣的未捕獲異常僅會被記錄日誌。

解答

Spring Boot會自動配置一個ThreadPoolTaskExecutor, 它屬於TaskExecutor, 如果是唯一的話就滿足了相關條件, 不會再使用org.springframework.core.task.SimpleAsyncTaskExecutor運行@Async的方法

1. Task Execution

1.1. 註解

  • @EnableAsync/@Async

1.2 重點類

  • ThreadPoolTaskExecutor
  • TaskExecutorBuilder

1.3 常規配置

spring.task.execution.pool.max-size=16
spring.task.execution.pool.queue-capacity=100
spring.task.execution.pool.keep-alive=10s

1.4 額外配置

默認的拒絕策略是AbortPolicy, 如果要修改的話就沒有辦法通過application.yaml設置了, 需要參考- How To Do @Async in Spring

2. Task Scheduling

1.1 註解

  • @EnableScheduling/@Scheduled

1.2 重點類

  • ThreadPoolTaskScheduler
  • TaskSchedulerBuilder

1.3 常規配置

spring.task.scheduling.thread-name-prefix=scheduling-
spring.task.scheduling.pool.size=2

1.4 額外配置

一般不涉及額外配置

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章