簡體   English   中英

春季:從Web App線程子線程(從ThreadPool)訪問請求(會話)范圍的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM