캐시 알고리즘을 구현해야 할 필요가 있을 때에, 가장 좋은 라이브러리가 바로 EhCache입니다.

EhCache를 사용하면 다음과 같은 장점이 있습니다.

Map 처럼 EhCache 인터페이스를 사용하여, Key에 매핑되는 Value 객체를 넣고 뺄 수 있다.
기본적으로 In-memory 캐시를 제공한다.
EhCache를 설정하는 XML 파일 (ehcache.xml) 을 잘 설정하게 되면, 다음과 같은 기능을 넣을 수 있다.
캐시에 저장될 엘리먼트 개수를 몇 개로 할지.. (기본값은 10,000개)
캐시 중에서 In-memory로 몇 개 In-Disk로 몇 개로 할지..
In-Disk로 저장하는 옵션 사용 여부
알고리즘: LRU 등..
캐시에 저장된 엘리먼트의 Expire 시간 설정
분산환경에서 여러 VM 간 동기화 옵션
등 등..
따라서, 그냥 Map 과 같은 걸로 캐시 알고리즘을 구현하는 것보다 매우 안전해진다.
왜냐하면 옵션에 따라 캐시에 사용되는 메모리 크기를 조절할 수 있으므로.
 

[간단한 사용방법]

 

1. 개발 및 런타임 환경

 

  – ehcache 라이브러리가 클래스패스에 추가되어야 함.

  – 다운로드를 위한 홈페이지 위치: http://ehcache.sourceforge.net/

  – ehcache-1.4.0-beta2.jar, backport-util-concurrent-3.0.jar, commons-logging-1.0.4.jar, jsr107cache-1.0.jar

 

2. Spring 설정 파일에 CacheManager 및 Cache Storage 객체 추가

 

    <!– 아래 cacheManager 는, 전체 EhCache를 관리하는 최상위 객체임 –>

    <bean id=”cacheManager” class=”org.springframework.cache.ehcache.EhCacheManagerFactoryBean”>

    </bean>

 

    <!– 아래 ehUserCache는 예제 Cache Storage로서, 여기서는 User 객체를 저장하는 Cache Storage임.

           기능별로 이러한 Bean을 여러 개 둘 수 있음: 예) ehBoardCache, ehMessageCache 등.

           cacheName 프로퍼티는 EhCache 내부에서 구별하는 Cache Storage 이름을 설정하는 것임.

           나중에 파일 저장하게 되면, 이 이름이 사용됨. –>

    <bean id=”ehUserCache” class=”org.springframework.cache.ehcache.EhCacheFactoryBean”>
        <property name=”cacheManager” ref=”cacheManager” />
        <property name=”cacheName” value=”userCache” />
    </bean>

3. Cache Storage 객체를 비즈니스 로직 Bean에서 참조

 

    예를 들어, 사용자 관리자 구성요소 (UserManager) 가 있다고 가정하면,

    그 클래스 이름이 com.hs.dir.UserManagerImpl 이라고 합시다.

    그러면,

 

    <bean id=”userManager” class=”com.hs.dir.UserManagerImpl”>
        <property name=”userCache” ref=”ehUserCache” />
    </bean>

 

    그리고 위 소스는 다음과 같은 예로 작성될 수 있습니다.

package com.hs.dir;

 

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

 

public class UserManagerImpl implements UserManager

{

    protected Ehcache userCache;

 

    public void setUserCache(Ehcache userCache)

    {

        this.userCache = userCache;

    }

 

    public Ehcache getUserCache()

    {

        return this.userCache;

    }

 

    public User getUser(String userName)

    {

        User user = null;

 

        Element cachedUserElement = this.userCache.get(userName);

 

        if (cachedUserElement != null)

        {

            user = (User) cachedUserElement.getValue();

        }

        else

        {

             user = retrieveUser(userName);

             cachedUserElement = new Element(userName, user);

             this.userCache.put(cachedUserElement);

        }

 

        return user;

    }

 

    protected User retrieveUser(String userName)

    {

        User user = null;

        // 데이터베이스 또는 디렉터리 서버로부터 사용자 정보 조회하여

        // User 객체 생성 로직이 여기 들어감..

        return user;

    }

}

 

4. ehcache.xml 설정 가이드

 

  – ehcache.xml 설정 가이드: http://users.handysoft.co.kr/~wsko/books/bpms-framework-doc/html/ehcache.html

  – ehcache.xml 설정을 바꾸는 경우, 해당 파일을 /WEB-INF/classes/ 디렉터리에 그 파일을 복사하면 적용된다.

Leave a Reply

Your email address will not be published. Required fields are marked *