【发布时间】:2020-12-18 02:36:33
【问题描述】:
我正在使用 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注解不应该有一些关键吗?
-
它也不适用于密钥。而且我认为我不需要特殊键,当缓存只有一个条目时。
-
从 Cacheable 文档中,如果您不指定键,默认情况下所有方法参数都被视为键。由于您将 hashmap 作为方法参数,因此解析的键可能总是不同的。您是否尝试过在方法调用之间保持相同的键?
-
您可以尝试使用#root.methodName 作为键吗?
-
@SKumar 完美!它正在工作!非常感谢。
标签: java spring-boot caching ehcache