Cannot find cache named xxx for Builder with Ehcache

Viewed 1036

Just trying Caching in spring boot for the first time and getting the following error

Request processing failed; nested exception is java.lang.IllegalArgumentException: Cannot find cache named 'PERSON_CACHE' for Builder[public java.util.Optional com.abdulsamadsyed.person.service.PersonService.findOne(java.lang.Long) throws java.lang.InterruptedException] caches=[PERSON_CACHE] | key='#id' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false'] with root cause

Can someone guide me if my configuration looks okay if not can someone suggest corrections?

Configuration Class

package com.abdulsamadsyed.person.Config;

import com.abdulsamadsyed.person.model.Person;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.ResourcePools;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.ehcache.CacheManager;
import java.time.Duration;

@Configuration
@EnableCaching
public class CacheConfig {
    public final static String PERSON_CACHE = "PERSON_CACHE";
    @Bean
    CacheManager ehCacheManager() {
        ResourcePools resourcePool = ResourcePoolsBuilder.heap(100).offheap(32, MemoryUnit.MB).build();
        CacheConfiguration configuration = CacheConfigurationBuilder
                .newCacheConfigurationBuilder(Integer.class, Person.class, resourcePool)
                .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(10)))
                .build();
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                .withCache(PERSON_CACHE, configuration)
                .build();
        cacheManager.init();
        return cacheManager;
    }
}

Usage class

@Cacheable(value = CacheConfig.PERSON_CACHE, key = "#{id}")
    public Optional<Person> findOne(Long id) throws InterruptedException {
        System.out.println("Prending Remote call");
        Thread.sleep(4000);
        return personRepository.findById(id);
   }

which is called from controller

@GetMapping("/persons/{id}")
    public Optional<Person> getPersons(@PathVariable Long id) throws InterruptedException {
        return personService.findOne(id);
}
0 Answers
Related