fork/join和线程池_从fork-join /线程池调用的Singelton bean中的访问spring请求范围缓存...
fork/join和線程池
問題:
啟用了Spring且其范圍設置為Request的緩存需要由不在請求范圍內的singleton bean訪問。
解:
Spring使您能夠創(chuàng)建緩存,該緩存為請求范圍保留數據。 例如
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但是有一種簡單的方法可以修復它:
2.將此屬性傳遞給來自pool或fork / join的自定義線程。 基本上可以通過在構造函數中使用此屬性創(chuàng)建可運行對象來完成
3.在調用標記為使用請求范圍緩存的方法之前,設置請求屬性
RequestContextHolder.setRequestAttributes(attributes);這將在當前線程的本地線程中設置屬性,該屬性可用于調用上述方法。
測試用例中的綜合要求
現在,如果您正在從junit測試方法,則可能根本沒有請求對象。
因此,您可以創(chuàng)建一個并按上述方法使用它來填充要測試的屬性
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请求范围缓存...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 世界上最恐怖的电脑病毒(世界上最恐怖的电
- 下一篇: 电脑鼓点节拍器(电子鼓点节拍器)