spring seurity集成spring boot使用DelegatingSecurityContextAsyncTaskExecutor类异步授权authentication登录登出退出信息@async
方法1:将SecurityContextHolder的策略更改为MODE_INHERITABLETHREADLOCAL
<beans:bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <beans:property name="targetClass" value="org.springframework.security.core.context.SecurityContextHolder"/> <beans:property name="targetMethod" value="setStrategyName"/> <beans:property name="arguments" value="MODE_INHERITABLETHREADLOCAL"/> </beans:bean>
方法2:将上面的方法用java方法实现
@Bean public MethodInvokingFactoryBean methodInvokingFactoryBean() { MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean(); methodInvokingFactoryBean.setTargetClass(SecurityContextHolder.class); methodInvokingFactoryBean.setTargetMethod("setStrategyName"); methodInvokingFactoryBean.setArguments(new String[]{SecurityContextHolder.MODE_INHERITABLETHREADLOCAL}); return methodInvokingFactoryBean; }
方法3:AsyncTaskExecutor
包装在DelegatingSecurityContextAsyncTaskExecutor
中,该DelegatingSecurityContextAsyncTaskExecutor
是专门为传播Spring SecurityContext设计的.另外,您还需要为安全上下文设置MODE_INHERITABLETHREADLOCAL
// 定义一个多线程执行器 @Bean("threadPoolTaskExecutor") public TaskExecutor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(20); executor.setMaxPoolSize(1000); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setThreadNamePrefix("Async-"); executor.initialize(); // this is important, otherwise an error is thrown return new DelegatingSecurityContextAsyncTaskExecutor(executor); // 把上面定义的多线程执行器放到异步任务中 }
// 在业务逻辑代码里面异步调用多线程执行器 @Override @Async("threadPoolTaskExecutor") public void yourLogic() { [..] }
方法4:将上面方法3的方法用xml实现
<task:annotation-driven executor="_importPool"/>
<task:executor id="_importPool" pool-size="5"/>
<bean id="importPool"
class="org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor">
<constructor-arg ref="_importPool"/>
</bean>
@Async("importPool") public void run(ImportJob import) { //业务逻辑代码,调用上面定义的多线程异步执行器 .... }
方法5:使用监听器实现
<bean id="applicationEventMulticaster" class="org.springframework.context.event.SimpleApplicationEventMulticaster"> <property name="taskExecutor"> <ref bean="delegateSecurityAsyncThreadPool"/> </property> </bean> <bean id="threadsPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> </bean> <bean id="delegateSecurityAsyncThreadPool" class="org.springframework.security.task.DelegatingSecurityContextTaskExecutor"> <constructor-arg ref="threadsPool"/> </bean>
@Async("delegateSecurityAsyncThreadPool") public void run(ImportJob import) { //业务逻辑代码,调用上面定义的多线程异步执行器 .... }
链接地址:https://stackoverflow.com/questions/5246428/spring-security-and-async-authenticated-users_mixed-up