EhCache ile Spring Boot Caching çalışmıyor

Aug 29 2020

HTTP yanıtını harici API'den önbelleğe almak için EhCache ve Spring Boot kullanıyorum, ancak önbellek çalışmıyor gibi görünüyor.

Thread.sleep (2000);Önbelleğe alınmış bir yanıt kullanırken atlanması gereken gecikmeyi simüle etmek için ekliyorum . Ancak bu değildir ve her yöntem çağrısı ile bir gecikme ve bir harici API de çağrılır.

İşte önbellek yapılandırma sınıfım

@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());
    }
}

Ve önbelleğe alınması gereken yöntem

    @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());
    }

Bunun neden işe yaramadığına dair bir fikrin var mı?

Tavsiyelerin için teşekkürler.

Yanıtlar

2 SKumar Aug 29 2020 at 18:21

Önbelleğe alınabilir ek açıklamada anahtar belirtilmediğinde, tüm yöntem parametreleri burada gerçekleşen bir anahtar olarak kabul edilir.

Bakın - https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html

key - Varsayılan "" dir, yani özel bir keyGenerator () yapılandırılmadıkça tüm yöntem parametreleri bir anahtar olarak kabul edilir.

TRANSPORT_LOCATIONS önbelleğinde yalnızca tek bir anahtara ihtiyacınız olduğundan, anahtar olarak yöntem adını belirtebilirsiniz.

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