我们有一个Spring Web应用程序。当网络服务器是码头时,API是用泽西岛实现的。
我们希望能够从父线程初始化的并行lambda表达式和多播Apache Camel路由访问请求范围的bean。
可以让子线程从父线程继承请求上下文(通过InheritableThreadLocal变量)。虽然问题是这些属性没有传递给子线程,因为它们从线程池重用(单独的lambda和camel's)。
也无法通过参数传递请求绑定信息 - 我们在项目中有太多需要更改的方法。
答案 0 :(得分:2)
您可以先获取参数
SecurityContext context = SecurityContextHolder.getContext();
RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
将它们设置在你的线程中
SecurityContextHolder.setContext(context);
RequestContextHolder.setRequestAttributes(attributes, true);
我在我的应用程序中遇到同样的问题,读取该文件作为休息请求的输入,逐行解析并将记录插入数据库。
但该文件包含超过5个lac记录,并且该过程花费了太多时间。所以我决定使用并行流。
以下代码为我工作
public void saveRecordsFromFile(MultipartFile file) {
// Getting security and request params
SecurityContext context = SecurityContextHolder.getContext();
RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
// Reading the file line by line and making rule
br.lines().parallel().forEach(line -> {
// Setting security and request params for current thread
SecurityContextHolder.setContext(context);
RequestContextHolder.setRequestAttributes(attributes, true);
saveRecord(line);
});
} catch (Exception ex) {
throw new SystemException("Error while input file", ex);
}
}