1 java spring spring-security threadpoolexecutor
我正在尝试在基于 Spring 的 Web 应用程序中使用并发机制。这样我就使用了以下方法来使用线程概念来获取员工详细信息。但由于线程上的 Spring 上下文为空,我因空指针异常而失败。
我使用了下面的代码:
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(10);
threadPool.initialize();
ExecutorServiceAdapter adapter = new ExecutorServiceAdapter(threadPool);
List<Callable<Employee>> tasks = new ArrayList<Callable<Employee>>();
for (int i = 0; i < employeeArr.length; i++) {
final int value = i;
tasks.add(new Callable<Employee>() {
public Employee call() throws Exception {
return empService.getEmployeeDetails(employeeArr[value], finalFromDate);
}
});
}
try {
List<Future<Employee>> result = adapter.invokeAll(tasks);
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i).get());
}
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
在“empService.getEmployeeDetails”方法中,我使用以下代码引用 Spring 上下文:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Collection<GrantedAuthority> authorities = auth.getAuthorities();
Run Code Online (Sandbox Code Playgroud)
但访问 spring 上下文时出现空指针异常。
有人可以帮我解决这个问题吗?
您可以利用org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor. 尝试这样的事情:
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
threadPool.setCorePoolSize(10);
threadPool.initialize();
TaskExecutor taskExecutor = new DelegatingSecurityContextAsyncTaskExecutor(threadPool);
ExecutorServiceAdapter adapter = new ExecutorServiceAdapter(taskExecutor);
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3452 次 |
| 最近记录: |