EhCache : Spring 로컬 캐시 라이브러리
Spring에서 간단히 사용할 수 있는 JAVA기반 오픈소스 캐시 라이브러리이다.
환경
- Spring Tool Suite 3
- ehcache 3
- application.yml
사용 이유
- index 키 값을 가지고 간단한 정보(자주 변동되지 않는 정보)를 알기 위한 DB접근을 줄이기 위해 -> 부담이 생김
- 또는 위와 같은 이유로 쿼리에서 매우 빈번히 발생하는 join을 줄이기 위해.
EhCahe 설정
1. Maven depandency
1) Maven dependency 추가 (pom.xml)
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
2) spring boot를 사용시 아래의 Maven dependency 추가 (pom.xml)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
spring boot를 사용한다면, spring-boot-starter-cache로 인해 캐시관련 설정이 간단해진다.
(CacheManager, EhCacheManagerFactoryBean등의 bean 설정을 안해도 된다.)
2. ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
<!-- 임시저장 경로 -->
<diskStore path="java.io.tmpdir"/>
<!-- default Cache 설정 (반드시 선언해야 하는 Cache) -->
<defaultCache
maxElementsInMemory="0"
eternal="true"
overflowToDisk="false"
memoryStoreEvictionPolicy="LFU"
/>
<cache name="oprtrCache"
maxElementsInMemory="0"
eternal="true"
timeToLiveSeconds="0"
timeToIdleSeconds="0"
overflowToDisk="false"
transactionalMode="off">
</cache>
</ehcache>
- defaultCache는 반드시 구현해야한다. (캐시의 기본설정) 없으면 에러발생한다.
- cache의 name속성은 캐시의 이름으로, 코드에서 name으로 Cache 인스턴스를 구한다.
cache 속성
속성 | 설명 | Default |
name | 캐시 이름 | 필수 |
maxEntriesLocalHeap | 메모리에 생성할 수 있는 최대 캐시 갯수 | 0 |
maxEntriesLocalDisk | 디스크에 생성할 수 있는 최대 캐시 갯수 | 0 |
eternal | 영속성 캐시 설정 (지워지는 캐시인지?) external = "true"이면, timeToIdleSecond, timeToLiveSeconds 설정이 무시됨 |
false |
timeToIdleSecond | 해당 초동안 캐시가 호출 되지 않으면 삭제 | 0 |
timeToLiveSeconds | 해당 초가 지나면 캐시가 삭제 | 0 |
overflowToDisk | 오버플로우 된 항목에 대해 disk에 저장할 지 여부 | false |
diskPersistent | 캐시를 disk에 저장하여, 서버 로드 시 캐시를 말아 둘지 설정 | false |
diskExpiryThreadIntervalSeconds | Disk Expiry 스레드의 작업 수행 간격 설정 | 0 |
memoryStoreEvictionPolicy | 캐시의 객체 수가 maxEntriesLocalHeap에 도달하면, 객체를 추가하고 제거하는 정책 설정 LRU : 가장 오랫동안 호출 되지 않은 캐시를 삭제 LFU : 호출 빈도가 가장 적은 캐시를 삭제 FIFO : First In First Out, 캐시가 생성된 순서대로 가장 오래된 캐시를 삭제 |
LRU |
https://kimyhcj.tistory.com/253
3. application.yml
EhCache xml 파일 지정
spring:
cache:
ehcache:
config: classpath:ehcache.xml
4. @EnableCaching
캐시 사용 어노테이션 추가
@SpringBootApplication
@EnableCaching
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
}
EhCache 사용 (CacheManager)
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class CacheEvent
{
// spring boot사용으로 따로 빈생성 안함
public CacheManager cacheManager;
public void test(){
// 캐시 인스턴스 생성
Cache cache = cacheManager.getCache("캐시이름");
// 캐시에 데이터 추가 및 수정
String key = "001"; // 키
Object obj = new Object(); // 값
Element element = new Element(key,obj); // 캐시 데이터
cache.put(element); // 캐시에 해당 키가 존재하지 않으면 추가, 존재하면 수정한다.
// 캐시 데이터 읽기
Element ele = cache.get(key);
if(ele != null)
{
obj = (Object) ele.getObjectValue();
}
// 캐시 데이터 삭제
cache.remove(key); // 해당 키값을 가진 데이터를 삭제한다.
}
}
1. Cache (net.sf.ehcache.Cache)
- Cache는 ehacahe의 클래스이다.
- Element 객체를 가지고 있고, CacheManager에 의하여 참조된다.
- 추가 및 수정 : put 메서드로 캐시에 요소를 넣는다. (키값이 이미 존재하면 수정, 존재하지 않으면 추가한다.)
- 제거 : remove 메서드로 캐시에서 해당 키 항목을 제거한다.
- 모두 제거 : removeAll 메서드로 캐시된 모든 항목 또는 인자로 받은 키 항목들을 제거한다.
- 읽기 : get 메서드로 인자로 받은 키를 가진 Element요소를 반환한다.
https://www.ehcache.org/apidocs/2.9/net/sf/ehcache/Cache.html
2. Element (net.sf.ehcache.Element)
- 키와 값으로 구성된 Cache의 요소이다.
- 키값은 자료형도 바라본다. (문자열 1과 숫자 1을 다른 키로 인식한다.)
- getObjectKey메소드로 Element개체의 키 속성을 Object로 가져올수 있다.
- getObjectValue메소드로 Element개체틔 값을 Object로 가져온다.
https://www.ehcache.org/apidocs/2.9/net/sf/ehcache/Element.html
3. CacheManager (net.sf.ehcache.CacheManager)
- CacheManager는 Cache 및 EhCache에 대한 참조를 제공해주고 생성 및 캐시 주명 주기를 관리한다.
- 캐시 추가 : accCache 메서드로 새로운 캐시를 추가한다.
- 캐시 읽기 : getCache 메서드로 해당 이름을 가진 캐시 인스턴스를 반환한다.
- 캐시 제거 : removeCache 메서드로 인자로 받은 이름을 가진 캐시를 CacheManager에서 제거한다.
- 종료 : shutdown 메서드로 CacheManager를 종료한다.
https://www.ehcache.org/apidocs/2.10.4/net/sf/ehcache/CacheManager.html
https://jaehun2841.github.io/2018/11/07/2018-10-03-spring-ehcache/#spring-cache-annotation