'Ehcache Spring Annotation'에 해당되는 글 1건

  1. 2012.09.18 EhCache의 Spring Framework(iBatis)적용...!
Java2012. 9. 18. 16:48

EhCache의 Spring Framework적용에 대해서 알아 보겠다.


동일한 데이터 요청을 여러번 할 경우 매번 그데이터를 Database에 접근해서 데이터를 가지고 온다면..


Database에는 큰 부하가 걸릴 것이다.


만약 이 요청한 데이터의 변하지 않는다면 Database를 거치지 않고 그대로 그 데이터를 저장하고 있다가


보내준다면 Database에는 무리가 덜 할 것이다.


그 기능을 해줄 것이 바로 Cache!!


이러한 고민을 나만 한것이 아니라 아마도 개발자들이 개발을 시작하면서 부터 계속 해왔을 것이다.


검색을 해보니 OSCache, JCS, EhCache등 여러 오픈 소스들이 있었다.


그중에 성능이 가장 좋고 또 사용 하기에 간편하고 Spring에서 Annotation설정 하나 만으로도 사용가능한


EhCache을 선택해 Spring에 적용을 해보았다.


EhCache를 iBatis에 바로 적용 시키는 방법도 있다.


하지만 EhCache는 Spring에서 지원(?) 콜라보레이션(?)을 하고 있다.


http://code.google.com/p/ehcache-spring-annotations/


위의 사이트에서 라이브러리를 다운 받자.


압축을 풀면 ehcache-spring-annotations-1.2.0.jar 파일과


lib폴더 안에는 Ehcache에 관련되 라이브러리들이 들어 있다.


이미 Spring Framework의 라이브러리를 추가해 놓았다면 그외에 필요한 라이브 러리를 프로젝트에 추가하자.


필요 한 라이브러리의 목록은 다음과 같다.


aopalliance-1.0.jar

commons-codec-1.5.jar

ehcache-core-2.4.5.jar

guava-r09.jar

slf4j-api-1.6.2.jar


라이브 러리 추가를 마쳤으니 이제는 설정!!


우선은 Spring Framework의 Application-Context.xml에 EhCache의 FactoryBean을 등록 해야한다.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
       xsi:schemaLocation="
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">
    <ehcache:annotation-driven cache-manager="ehCacheManager" />
   
    <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="/WEB-INF/config/ehcache.xml" />
    </bean>

</beans>

붉은색으로 표시된 부분을 추가 해줘야 한다.


FactoryBean추가 부분을 보면 Property의 configLocation이 있는데 여기엔 EhCache설정 파일의 경로를 적어 주어야 한다.


다음은 EhCache의 설정 파일 부분이다.


<?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" />
   
    <cacheManagerPeerProviderFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
        properties="peerDiscovery=manual,
                    rmiUrls=//192.168.0.99:2424/TalkMsg.channelTalkCache"/>
    <cacheManagerPeerListenerFactory
    class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
    properties="port=2424, socketTimeoutMillis=120000" />
   
    <defaultCache eternal="false"  
        maxElementsInMemory="5000" 
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="false"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU">
    </defaultCache>
   
    <cache name="cache1"
        maxElementsInMemory="5000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="false"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU">
        <cacheEventListenerFactory
           class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
           properties="replicateAsynchronously=false,replicateUpdatesViaCopy=false" />
          
        <bootstrapCacheLoaderFactory
                 class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
           properties="bootstrapAsynchronously=false,
                     maximumChunkSizeBytes=5000000" />
    </cache>
</ehcache>

설정 파일 안에는 캐쉬를 어떻게 사용할지에 대해서 설정을 한다.


cacheManagerPeerProviderFactory와 cacheManagerPeerListenerFactory는 캐시 서버가 여러대일 경우


다른 서버와의 동기화에 필요한 설정들이다.


그리고 defaultCache는 꼭 있어야 하는 캐쉬 설정이며, cache name="cache1"는 내가 프로젝트내에서 사용할 캐쉬의 설정.


그외 설정의 세부적인 부분은 이후의 포스팅에 다룰것이다.


EhCache는 Java RMI를 이용하여 다른 캐시 서버와의 통신을 한다.


그럼 마지막으로 캐시를 적용할 부분을 보자.


@Override
    @Cacheable(cacheName="cache1")
    public List<?> getList(Map<String, Object> param) {
        return getSqlMapClientTemplate().queryForList("TalkMsg.getTalkMsgList", param);
    }

    @Override
    @TriggersRemove(cacheName="cache1", removeAll=true)
    public Object insertMsg(Map<String, Object> param) {
        return getSqlMapClientTemplate().insert("TalkMsg.insertTalkMsg", param);
    }

Annotation만으로도 설정이 가능하다.


단순히 List만을 가져오는 경우에는 캐시를 가져와 저장하고 또 불러오기 전 캐시에 내가 원하는 데이터가 있는지 확인하는


Annotation인 @Cacheble를 사용하고 데이터 삽입, 삭제, 수정같은 데이터의 변화가 있을 경우에는 @TriggerRemove


Annotation을 이용하여 캐시의 내용을 모두 지워 데이터의 유효성을 높인다.


이 세가지의 설정만으로 캐시는 정상적으로 잘 작동한다.


영어가 된다면 EhCache의 공식 홈페이지에 가는것을 권장한다.


설정이 너무 간단하다 보니 영어만 좀 된다면 공식 홈페이지의 내용을 보는것이 좀더 정확하고 빠를 것 같다.


EhCache는 단순하고 가볍고 거기에 성능까지 좋다는 평을 받고 있다.


실제로 설정을 하고 사용을 해보니 정말 편하고 성능도 좋았다.


이 이후의 포스팅은 설정의 세세한 부분과 성능 테스트가 될것이다.


그리고 내가 올린 포스팅은 잘못 된 정보가 있을 것이니 참고만 하고 공식 홈페이지의 내용이나 공식 홈페이지에서 제공하는


문서를 주로 참고 할 것을 권장한다.

'Java' 카테고리의 다른 글

Java Server Timeout Test하기.  (0) 2013.02.05
Https SSLHandshakeException..!  (0) 2012.10.16
json-lib-2.4-jdk15.jar  (0) 2012.08.24
Log4j의 Appender..!  (0) 2012.06.26
Log4j 설정..!  (0) 2012.06.25
Posted by Z700zZz