【问题标题】:Spring context is not getting updated even after using DelegatingSecurityContextAsyncTaskExecutor即使在使用 DelegatingSecurityContextAsyncTaskExecutor 之后,Spring 上下文也没有得到更新
【发布时间】:2021-07-25 03:48:49
【问题描述】:

我在使用 spring 上下文时遇到了一些问题,在阅读了所有文章后,它确实变得更加混乱。 所以,这是我的用例:

我有一个正在运行的应用程序,它需要在请求中传递用户的身份验证令牌才能在我将在后台运行的进程中使用它。此令牌用于进行 rest api 调用。起初,我们手动创建新线程并传递上下文,我使用 MODE_INHERITABLETHREADLOCAL 策略作为 spring 上下文。但在最新版本中,我们开始使用线程池。它在部署后工作,但令牌在某个点之后变得无效,因为线程没有获得最新的上下文。我阅读了文章并开始使用 DelegatingSecurityContextAsyncTaskExecutor,如下所示:

@豆 公共 DelegatingSecurityContextAsyncTaskExecutor taskExecutor(ThreadPoolTask​​Executor 委托) { 返回新的 DelegatingSecurityContextAsyncTaskExecutor(delegate); }

但是我今天检查时仍然遇到同样的问题。现在明天我可能会收到来自测试员的邮件,其中包含失败的测试用例。我想补充一点,我仍然使用 MODE_INHERITABLETHREADLOCAL 作为策略以及 DelegatingSecurityContextAsyncTaskExecutor。请帮帮我。

【问题讨论】:

    标签: spring-boot spring-mvc spring-security threadpool spring-context


    【解决方案1】:

    首先:您不应该将MODE_INHERITABLETHREADLOCAL 与池线程一起使用(要了解更多信息,请阅读this

    第二:根据我的经验,将DelegatingSecurityContextAsyncTaskExecutor 定义为@Bean 是行不通的。仍将使用默认执行器。

    您需要从AsyncConfigurer 接口扩展您的@EnableAsync @Configuration 并实现getAsyncExecutor,而不是使用@Bean 对其进行注释。工作示例:

    @EnableAsync
    @Configuration
    public class AsyncConfig implements AsyncConfigurer {
        private final ThreadPoolTaskExecutor defaultSpringBootAsyncExecutor;
    
        public AsyncConfig(ThreadPoolTaskExecutor defaultSpringBootAsyncExecutor) {
            this.defaultSpringBootAsyncExecutor = defaultSpringBootAsyncExecutor;
        }
    
        @Override
        public Executor getAsyncExecutor() {
            return new DelegatingSecurityContextAsyncTaskExecutor(defaultSpringBootAsyncExecutor);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-14
      • 2023-04-07
      • 1970-01-01
      • 2017-09-24
      相关资源
      最近更新 更多