2017-08-02 41 views
1

我們有一個Spring Web應用程序。在Web服務器是jetty的情況下,API使用Jersey實現。Spring:從Web應用程序線程訪問請求(會話)作用域Bean線程(來自線程池)

我們希望能夠從並行lambda表達式和多線程Apache Camel路由中訪問請求作用域bean,並由父線程初始化。

可以讓子線程從父線程繼承請求上下文(通過InheritableThreadLocal變量)。雖然問題是這些屬性是沒有傳遞給子線程,因爲它們是從線程池(單獨的lambda和駱駝)重新使用。

無法通過參數傳遞請求綁定信息 - 我們在項目中有太多需要更改的方法。

回答

0

您可以通過首先得到的參數

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); 
    } 
}