스프링에서는 포괄적인 캐시 추상 인터페이스를 이용하여, ehcache를 구현할 수 있습니다. (3.1부터? 2.5부터?)
그래서 메소드에 어노테이션으로 @Cacheable 이나 @CacheEvict 와 같이 코드에 추가하여 개발자로 하여금 쉽게 사용할 수 있게 하고 있습니다.
하지만 당연하게도 어노테이션만으로 구현되지는 않으나 기본적인 추가내용이 어렵지는 않습니다.
아래의 단계를 거치면 기본적인 cache 구현을 사용할 수 있습니다.
1. dependency 추가
A. gradle
compile('net.sf.ehcache:ehcache')
B. maven
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId> ehcache </artifactId>
<version>2.10.4</version>
</dependency>
2. ehcache.xml 생성
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocatioin="ehcache.xsd"
updateCheck="true"
dynamicConfig="true"
maxBytesLocalHeap="4M">
<cache name="testName"
maxBytesLocalHeap="2M"
memoryStoreEvictionPolicy="LRU" // LFU, FIFO
timeToLiveSeconds="3600">
</cache>
</ehcache>
3. CacheManager config 생성
@EnableCaching
@Configuration
public class MyCacheConfig {
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheManager() {
EhCacheManagerFactoryBean bean = new EhCacheManagerFactoryBean();
bean.setConfigLocation(new ClassPathResource("ehcache.xml"));
bean.setShared(true);
}
}
4. 메소드에 @Cacheable 어노테이션으로 사용
/**
* 기본적으로 key-value 형태이며, 캐시이름으로 값이 없으면 만들고 조건을 줄 수 있다.
*/
@Cacheable("testName")
@Cacheable(cacheNames = "testName", key="#{keyId}")
@Cacheable(value = "testName", key="#{keyId}")
@CachePut(cacheNames = "testName") // 캐시를 갱신한다.
@CacheEvict(cacheNames = "testName", allEntries = true) // 캐시를 삭제한다.
※ 주의사항으로 같은 클래스 내의 호출(self-invocation)은 안 되니 유의해야한다.
5. 간단한 CacheManager TEST-CASE.
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@Import(MyCacheConfig.class)
public class MyCacheConfigTest {
@Autowired CacheManager cacheManager;
@Test public void testSample() {
Cache cache = cacheManager.getCache("testName");
cache.put("testKey", "testValue");
System.out.println("- cache=" + cache.get("testKey").get());
}
}
ref) https://spring.io/guides/gs/caching/
ref) https://memorynotfound.com/spring-boot-ehcache-2-caching-example-configuration/