簡體   English   中英

帶有 EhCache 的 Spring Boot 緩存不起作用

[英]Spring Boot Caching with EhCache doesn't work

我正在使用 EhCache 和 Spring Boot 來緩存來自外部 API 的 HTTP 響應,但緩存似乎不起作用。

我正在添加Thread.sleep (2000); 模擬使用緩存響應時應跳過的延遲。 但事實並非如此,每次調用方法時,還會調用延遲和外部 API。

這是我的緩存配置類

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

    private static final String TRANSPORT_LOCATIONS = "transportLocations";
    private static final int TTL_MILLISECONDS = 15;

    @Bean
    public net.sf.ehcache.CacheManager ehCacheManager() {
        CacheConfiguration transportLocationCache = new CacheConfiguration();
        transportLocationCache.setName(TRANSPORT_LOCATIONS);
        transportLocationCache.setMaxEntriesLocalHeap(1000);
        transportLocationCache.setMemoryStoreEvictionPolicy("LRU");
        transportLocationCache.setTimeToLiveSeconds(TTL_MILLISECONDS);

        net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
        config.addCache(transportLocationCache);
        return net.sf.ehcache.CacheManager.newInstance(config);
    }

    @Bean
    @Override
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManager());
    }
}

和方法,應該被緩存

    @Cacheable(value = TRANSPORT_LOCATIONS, cacheManager = "cacheManager")
    public HttpResponse<String> sendTransportLocationsPostRequest(
            final LinkedHashMap<String, Object> bodyStructure,
            final String url)
            throws Exception {
        Thread.sleep(2000);
        final String body = buildBody(bodyStructure);
        final HttpRequest request = buildPostRequest(url, body);

        return client.send(request, HttpResponse.BodyHandlers.ofString());
    }

你有什么想法,為什么這不起作用?

謝謝你的建議。

當 Cacheable 注釋中未指定 key 時,則所有方法參數都被視為發生在這里的 key。

參考 - https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html

key - 默認為 "",意味着所有方法參數都被視為一個鍵,除非已配置自定義 keyGenerator()。

由於您只需要 TRANSPORT_LOCATIONS 緩存中的單個鍵,您可以指定方法名稱作為鍵

@Cacheable(value = TRANSPORT_LOCATIONS, cacheManager = "cacheManager", key = "#root.methodName")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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