Spring Boot Caching ด้วย EhCache ไม่ทำงาน
ฉันใช้ EhCache และ Spring Boot เพื่อแคชการตอบสนอง HTTP จาก API ภายนอก แต่ดูเหมือนว่าแคชจะไม่ทำงาน
ฉันกำลังเพิ่ม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());
}
คุณมีความคิดหรือไม่ทำไมจึงใช้ไม่ได้?
ขอบคุณสำหรับคำแนะนำของคุณ
คำตอบ
เมื่อไม่ได้ระบุคีย์ในคำอธิบายประกอบที่ใช้แคชได้พารามิเตอร์วิธีการทั้งหมดจะถือเป็นคีย์ที่เกิดขึ้นที่นี่
อ้างถึง - https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html
คีย์ - ค่าเริ่มต้นคือ "" ซึ่งหมายความว่าพารามิเตอร์เมธอดทั้งหมดถือเป็นคีย์เว้นแต่จะมีการกำหนดค่า keyGenerator () ที่กำหนดเอง
เนื่องจากคุณต้องการเพียงคีย์เดียวในแคช TRANSPORT_LOCATIONS คุณจึงสามารถระบุชื่อเมธอดเป็นคีย์ได้
@Cacheable(value = TRANSPORT_LOCATIONS, cacheManager = "cacheManager", key = "#root.methodName")