![](/img/trans.png)
[英]Spring boot. The profit of using @ConfigurationProperties annotation
[英]Spring boot. How to Create TaskExecutor with Annotation?
我在 Spring Boot 应用程序中做了一个@Service
类,其中一种方法应该异步运行。 当我阅读方法时,方法应该被@Async
注释,而且我必须运行一个TaskExecutor
bean。 但是在 Spring 手册http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html 中,我没有找到任何信息或示例如何在没有 XML 配置的情况下使用注释运行TaskExecutor
。 是否可以在没有 XML 的情况下在 Spring Boot 中创建TaskExecutor
bean,仅使用注释? 这是我的服务类:
@Service
public class CatalogPageServiceImpl implements CatalogPageService {
@Override
public void processPagesList(List<CatalogPage> catalogPageList) {
for (CatalogPage catalogPage:catalogPageList){
processPage(catalogPage);
}
}
@Override
@Async("locationPageExecutor")
public void processPage(CatalogPage catalogPage) {
System.out.println("print from Async method "+catalogPage.getUrl());
}
}
将@Bean
方法添加到您的 Spring Boot 应用程序类:
@SpringBootApplication
@EnableAsync
public class MySpringBootApp {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
return executor;
}
public static void main(String[] args) {
// ...
}
}
有关如何使用 Java 配置而不是 XML 配置 Spring 的信息,请参阅 Spring Framework 参考文档中的基于 Java 的容器配置。
(注意:您不需要将@Configuration
添加到类中,因为@SpringBootApplication
已经包含了@Configuration
)。
首先——让我们回顾一下规则——@Async 有两个限制:
所以你的 processPage() 方法应该在单独的类中
更新:从Spring Boot 2.2 开始,不需要通过代码创建ThreadPoolTaskExecutor
。 事实上, ThreadPoolTaskExecutor
是默认的,并且可以使用以spring.task.execution
为前缀的属性完全配置。
所以,步骤:
@Configuration
@EnableAsync
类中使用@EnableAsync
,@Async
注释一个或多个方法ThreadPoolTaskExecutor
配置属性示例:
spring.task.execution.pool.core-size=1
spring.task.execution.pool.max-size=20
spring.task.execution.pool.keep-alive=120s
spring.task.execution.pool.queue-capacity=1000
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=5m
spring.task.execution.thread-name-prefix=async-executor-
spring.task.execution.pool.allow-core-thread-timeout=false
如果需要更多自定义,还可以实现TaskExecutorCustomizer
接口,例如(在 kotlin 中):
@Component
class AsyncExecutorCustomizer : TaskExecutorCustomizer {
override fun customize(taskExecutor: ThreadPoolTaskExecutor?) {
taskExecutor?.let { executor ->
executor.setRejectedExecutionHandler(ThreadPoolExecutor.CallerRunsPolicy())
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.