Spring Boot 应用程序中的线程技术和并行性

Spring Framework 通过使用 TaskExecutor 接口提供用于异步执行任务的抽象。 执行程序是线程池概念的 Java SE 名称。 Spring 的 TaskExecutor 接口与 java.util.concurrent.Executor 接口相同。 最初创建 TaskExecutor 是为了在需要时为其他 Spring 组件提供线程池的抽象。 Spring 包含 TaskExecutor 的许多预先构建的实现,但它是 DefaultManagedTaskExecutor ,当它查找应用程序服务器的 defaultExecutor (在 CICS Liberty 中设计为提供支持 CICS 的线程) 时,它最有助于与 CICS 集成。

关于此任务

要使用启用了 CICS 的线程在 Spring Boot 应用程序中运行异步任务,有两个选项。 您可以为整个应用程序设置异步执行程序,也可以选择按方法指定 AsyncExecutor 。 如果您异步衍生的所有任务都需要 CICS 服务,那么为整个应用程序设置异步执行程序是最简单的方法。 否则,您需要指定要用于需要异步功能的每个方法的异步执行程序。 在这里,我们演示了整个应用方法。

过程

  1. 在主 Spring Boot 应用程序类上,添加 @EnableAsync 注释,实现接口 AsyncConfigurer,并覆盖 getAsyncExecutor ()AsyncUncaughtExceptionHandler 方法。 确保在 getAsyncExecutor () 方法中返回 DefaultManagedTaskExecutor 的实例,因为这将从 Liberty 的 defaultExecutor获取新线程,而后者又配置为返回支持 CICS 的线程。 有关 AsyncConfigurer的更多信息,请参阅 Spring Boot 文档中的 AsyncConfigurer 。 有关用法示例,请参阅 Spring Boot 文档中的 EnableAsync
    @SpringBootApplication
    @EnableAsync
    public class MyApplication implements AsyncConfigurer 
    {     
    
        public static void main(String[] args) 
        {
            SpringApplication.run(MyApplication.class, args);
        } 
    
        @Override
        @Bean(name = "CICSEnabledTaskExecutor") 
        public Executor getAsyncExecutor() 
        { 
            return new DefaultManagedTaskExecutor();
        }
    
        @Override 
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() 
        {
            return new CustomAsyncExceptionHandler();
        }
    } 
    
    public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler 
    {
        @Override 
        public void handleUncaughtException(Throwable throwable, Method method, Object... obj) 
        {
            System.out.println("Exception Cause - " + throwable.getMessage());
            System.out.println("Method name - " + method.getName()); 
            for (Object param : obj) 
            {
                System.out.println("Parameter value - " + param);
            } 
        }
    }
  2. 将 @Async 注释添加到应用程序中的类 (如果您希望以异步方式运行该类上的所有方法) 或添加到您希望以异步方式运行的各个方法。 例如,@Async("CICSEnabledTaskExecutor")
  3. 将 concurrent-1.0 功能部件添加到 server.xml