您可以通过首先得到的参数
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);
}
}