[英]Instantiating a session scoped managed bean from another request scoped bean
[英]Spring: Accessing Request (Session) Scoped Bean from Web App Thread Child Threads (from ThreadPool)
我们有一个Spring Web应用程序。 当网络服务器停泊时,API是使用Jersey实施的。
我们希望能够从并行lambda表达式和多播Apache Camel路由(由父线程初始化)访问请求范围的Bean。
可以让子线程(通过InheritableThreadLocal变量)从父线程继承请求上下文。 虽然问题是,这些属性不会传递给子线程 ,因为他们是从线程池 (单独的Lambda和骆驼) 重新使用 。
也不能通过参数传递请求绑定信息-我们项目中有太多方法需要更改。
您可以先获取参数
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.