gpt4 book ai didi

java - 定制/扩展Spring对shiro的@Async支持

转载 作者:行者123 更新时间:2023-11-29 04:25:02 27 4
gpt4 key购买 nike

我正在使用 Spring 的 @EnableAsync 功能来异步执行方法。为了安全起见,我使用 Apache Shiro。在异步执行的代码中,我需要访问附加到触发异步调用的线程的 Shiro 主题。

Shiro 支持在不同线程中使用现有主题,方法是将主题与要在不同线程上执行的 Callable 相关联(请参阅 here ):

Subject.associateWith(Callable)

不幸的是,我无法直接访问Callable,因为这些东西是由 Spring 封装的。我发现我需要扩展 Spring 的 AnnotationAsyncExecutionInterceptor 来将我的主题与创建的 Callable 关联起来(这是最简单的部分)。

现在的问题是如何让 Spring 使用我的自定义 AnnotationAsyncExecutionInterceptor 而不是默认的。默认值是在 AsyncAnnotationAdvisorAsyncAnnotationBeanPostProcessor 中创建的。我当然也可以扩展这些类,但这只会变成问题,因为我需要让 Spring 再次使用我的扩展类。

有什么办法可以实现我想要的吗?

我也可以添加一个新的自定义异步注释。但我认为这不会有太大帮助。


更新:实际上,我发现 AnnotationAsyncExecutionInterceptor 需要自定义是错误的。一次偶然的机会,我偶然发现了 org.apache.shiro.concurrent.SubjectAwareExecutorService ,它的功能非常符合我的要求,这让我觉得我可以简单地提供一个自定义执行器,而不是自定义拦截器。详情请参阅我的回答。

最佳答案

通过提供ThreadPoolTask​​Executor的扩展版本,我设法实现了我想要的目标 - shiro subject自动绑定(bind)和取消绑定(bind)到由spring的异步支持执行的任务:

public class SubjectAwareTaskExecutor extends ThreadPoolTaskExecutor {

@Override
public void execute(final Runnable aTask) {
final Subject currentSubject = ThreadContext.getSubject();
if (currentSubject != null) {
super.execute(currentSubject.associateWith(aTask));
} else {
super.execute(aTask);
}
}

... // override the submit and submitListenable method accordingly
}

为了让 spring 使用这个执行器,我必须实现一个返回我的自定义执行器的 AsyncConfigurer:

@EnableAsync
public class AsyncConfiguration implements AsyncConfigurer {

@Override
public Executor getAsyncExecutor() {
final SubjectAwareTaskExecutor executor = new SubjectAwareTaskExecutor();
executor.setBeanName("async-executor");
executor.setCorePoolSize(10);
executor.setMaxPoolSize(10);
executor.initialize();
return executor;
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}

通过此更改,父线程的主题将自动在使用 @Async 注释的方法中可用,并且 - 可能更重要 - 执行该主题后,该主题将与线程解除连接异步方法。

关于java - 定制/扩展Spring对shiro的@Async支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46830264/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com