日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

fork/join和线程池_从fork-join /线程池调用的Singelton bean中的访问spring请求范围缓存...

發布時間:2023/12/3 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 fork/join和线程池_从fork-join /线程池调用的Singelton bean中的访问spring请求范围缓存... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

fork/join和線程池

問題:

啟用了Spring且其范圍設置為Request的緩存需要由不在請求范圍內的singleton bean訪問。

解:

Spring使您能夠創建緩存,該緩存為請求范圍保留數據。 例如

import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.cache.interceptor.SimpleCacheResolver; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; import java.util.ArrayList; import java.util.Collection; @Component @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) public class RequestScopeCache extends SimpleCacheResolver { public RequestScopeCache() { SimpleCacheManager cacheManager = new SimpleCacheManager(); Collection caches = new ArrayList((Collection) new ConcurrentMapCache( "myCache" , true )); cacheManager.setCaches(caches); cacheManager.initializeCaches(); setCacheManager(cacheManager); } }

您可以在要緩存的任何方法周圍使用此緩存

@Cacheable(value = "myCache" , cacheResolver = "requestScopeCache" ) public String getName(String id) { //logic to get name from id }

現在,如果您從具有請求上下文的任何控制器中調用此方法,那就很好了,即,該方法是從服務Web請求的Spring bean的任何其他方法中調用的。

但是,如果您需要從線程池或fork連接池中調用它,事情就會變得棘手。 假設您收到一個請求,并且需要生成多個線程以同時運行以收集數據以將請求存儲到服務器。

這些線程耗盡了Web請求線程的上下文,因此在Web請求線程上設置的任何“線程本地”值將對這些線程不可用。

因此,如果最終從這些池線程中調用上述方法(注釋為使用緩存),則會從spring中獲取異常,例如:

Scope 'session' is not active for the current thread ; IllegalStateException: No ; IllegalStateException: No thread -bound request found

但是有一種簡單的方法可以修復它:

  • 從Web請求線程獲取請求屬性
  • RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

    2.將此屬性傳遞給來自pool或fork / join的自定義線程。 基本上可以通過在構造函數中使用此屬性創建可運行對象來完成

    3.在調用標記為使用請求范圍緩存的方法之前,設置請求屬性

    RequestContextHolder.setRequestAttributes(attributes);

    這將在當前線程的本地線程中設置屬性,該屬性可用于調用上述方法。

    測試用例中的綜合要求

    現在,如果您正在從junit測試方法,則可能根本沒有請求對象。

    因此,您可以創建一個并按上述方法使用它來填充要測試的屬性

    RequestContextHolder.setRequestAttributes( new ServletRequestAttributes( new DummyRequest()));

    翻譯自: https://www.javacodegeeks.com/2020/05/access-spring-request-scope-cache-in-singelton-bean-called-from-fork-join-thread-pool.html

    fork/join和線程池

    總結

    以上是生活随笔為你收集整理的fork/join和线程池_从fork-join /线程池调用的Singelton bean中的访问spring请求范围缓存...的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。