본문 바로가기
  • A space that records me :)
기술/Cache

[Spring] EhCache 사용

by yjkim_97 2020. 11. 19.

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

 

Ehcache 옵션 정리

Ehcache 에 대해서는 이전글 참고 : 2013/12/24 - [IT/Spring] - ehcache diskExpiryThreadIntervalSeconds: 디스크에 저장된 캐시들에 대해 만료된 항목를 제거하기 위한 쓰레드를 실행 할 주기 설정 diskSpoolBu..

kimyhcj.tistory.com

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

 

Cache (ehcache 2.9.0 API)

Cache(String name, int maxElementsInMemory, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds)           1.1 Constructor. Cache(String na

www.ehcache.org

 

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

 

Element (ehcache 2.9.0 API)

Element(Object key, Object value, long version, long creationTime, long lastAccessTime, long hitCount, boolean cacheDefaultLifespan, int timeToLive, int timeToIdle, long lastUpdateTime)           Constructor used by ElementData. Element

www.ehcache.org

 

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

 

CacheManager (ehcache 2.10.4 API)

Returns a concrete implementation of Cache, it it is available in the CacheManager. Consider using getEhcache(String name) instead, which will return decorated caches that are registered. If a decorated ehcache is registered in CacheManager, an undecorated

www.ehcache.org

 


https://jaehun2841.github.io/2018/11/07/2018-10-03-spring-ehcache/#spring-cache-annotation

 

Cache에 대하여.. (Spring+EHCache) | Carrey`s 기술블로그

들어가며.. 엔터프라이즈 급 Application에서는 DBMS의 부하를 줄이고, 성능을 높이기 위해 캐시(Cache)를 사용한다. 우리 회사에서도 EHCache, Redis를 사용하지만, EHCache쪽은 공부한 적이 없어서 이번 기

jaehun2841.github.io

 

https://jaehun2841.github.io/2018/11/07/2018-11-04-ehcache-config-for-springframework/#maven-dependency-%EC%84%A4%EC%A0%95

 

EHCache 설정방법 (Spring Framework) | Carrey`s 기술블로그

EHCache 설정하기 설정 순서는 아래와 같다. Maven Dependency 설정 Ehcache.xml 작성 (ehcache 설정파일) CacheManager 설정 (xml) Maven Dependency 설정 1234567891011121314151617181920 net.sf.ehcache ehcache 2.10.6 org.springframework sp

jaehun2841.github.io