若依框架扩展支持异步线程池,并且能够将线程用户进行继承。

扩展SecurityConfig

扩展configure(HttpSecurity httpSecurity)

添加SecurityContextPersistenceFilter过滤器

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    // 注解标记允许匿名访问的url
    ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
    permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
	// ...
    // 添加 SecurityContextPersistenceFilter 过滤器,用于在请求线程和异步执行线程之间共享 SecurityContext 上下文信息
    httpSecurity.addFilterBefore(new SecurityContextPersistenceFilter(), WebAsyncManagerIntegrationFilter.class);
    // ...
    
}
            

线程池

@Bean(name = "applicationEventExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(10);
    executor.setMaxPoolSize(50);
    executor.setQueueCapacity(100);
    executor.setThreadNamePrefix("applicationEventThread-");
    executor.setTaskDecorator(securityContextTaskDecorator());
    executor.initialize();
    return executor;
}

@Override
public Executor getAsyncExecutor() {
    return taskExecutor();
}

异步异常处理器getAsyncUncaughtExceptionHandler

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

异步任务装饰器

@Bean
public TaskDecorator securityContextTaskDecorator() {
    return runnable -> {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        return () -> {
            try {
                SecurityContextHolder.setContext(securityContext);
                runnable.run();
            } finally {
                SecurityContextHolder.clearContext();
            }
        };
    };
}
Logo

快速构建 Web 应用程序

更多推荐