您可以通過首先得到的參數
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);
}
}