繁体   English   中英

弹簧靴。 如何使用注解创建 TaskExecutor?

[英]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为前缀的属性完全配置

所以,步骤:

  1. @Configuration @EnableAsync类中使用@EnableAsync
  2. 使用@Async注释一个或多个方法
  3. 可选地使用属性覆盖默认的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM