[英]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。
key - 默认为 "",意味着所有方法参数都被视为一个键,除非已配置自定义 keyGenerator()。
由于您只需要 TRANSPORT_LOCATIONS 缓存中的单个键,您可以指定方法名称作为键
@Cacheable(value = TRANSPORT_LOCATIONS, cacheManager = "cacheManager", key = "#root.methodName")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.