Spring Framework 通过使用 TaskExecutor 接口提供用于异步执行任务的抽象。 执行程序是线程池概念的 Java™ SE 名称。 Spring 的 TaskExecutor 接口与 java.util.concurrent.Executor 接口相同。 最初创建 TaskExecutor 是为了在需要时为其他 Spring 组件提供线程池的抽象。 Spring包含许多预构建 TaskExecutor ,但 DefaultManagedTaskExecutor 对于与 CICS® 集成最为有用,因为它会查找defaultExecutor ——在 CICS 中,它被设计为提供CICS线程。
关于此任务
要使用启用了 CICS 的线程在 Spring Boot 应用程序中运行异步任务,有两个选项。 您可以为整个应用程序设置异步执行程序,也可以选择按方法指定 AsyncExecutor 。 如果您异步衍生的所有任务都需要 CICS 服务,那么为整个应用程序设置异步执行程序是最简单的方法。 否则,您需要指定要用于需要异步功能的每个方法的异步执行程序。 在这里,我们演示了整个应用方法。
过程
- 在您的Spring Boot类上添加 @EnableAsync ,实现接口 AsyncConfigurer, ,并覆盖 getAsyncExecutor( 和 AsyncUncaughtExceptionHandler 方法。 确保您返回 DefaultManagedTaskExecutor 的实例,方法是使用 getAsyncExecutor( ),因为该方法从Liberty的 defaultExecutor, 获取新线程,而Liberty的配置是返回启用 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);
}
}
}
- 将 @Async 注释添加到应用程序中的类 (如果您希望以异步方式运行该类上的所有方法) 或添加到您希望以异步方式运行的各个方法。 例如,
@Async("CICSEnabledTaskExecutor")
- 将 concurrent-1.0 功能部件添加到 server.xml