본문 바로가기

Development/Web & Server

[Spring Framework] Ehcache 사용하기

1. 라이브러리 세팅~! 


<dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-context-support</artifactId>

  <version>${org.springframework-version}</version>

</dependency>


<dependency>

<groupId>com.googlecode.ehcache-spring-annotations</groupId>

<artifactId>ehcache-spring-annotations</artifactId>

<version>1.1.3</version>

</dependency>

<dependency>

<groupId>net.sf.ehcache</groupId>

<artifactId>ehcache</artifactId>

<version>2.7.4</version>

</dependency>


2. 설정파일 작성


<?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:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"

xsi:schemaLocation="http://www.springframework.org/schema/beans 

          http://www.springframework.org/schema/beans/spring-beans.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">

                 

      <!-- declare ehCache -->

  <ehcache:annotation-driven cache-manager="cacheManager" />

                 

  <!-- ehCache bean -->

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

    <property name="configLocation"  value="classpath:ehcache.xml"/>

  </bean>

                  

</beans> 


3. 캐쉬설정파일 작성 (ehcache.xml 파일이며 스프링 프로젝트에서 resource에 위치함)


<?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">   

    

    <defaultCache 

    eternal="false" 

    maxElementsInMemory="1000"

        overflowToDisk="false" 

        diskPersistent="false" 

        timeToIdleSeconds="0"

        timeToLiveSeconds="600" 

        memoryStoreEvictionPolicy="LRU"/>


    <cache 

    name="testCache1" 

    eternal="false"

        maxElementsInMemory="100" 

        overflowToDisk="false" 

        diskPersistent="false"

        timeToIdleSeconds="0" 

        timeToLiveSeconds="30"

        memoryStoreEvictionPolicy="LRU" />

        

</ehcache>


4.  캐쉬 사용하기 

  cacheable 애노테이션과 캐쉬설정파일에서 작성한  testCache1 를사용한다.


@Cacheable(cacheName="testCache1")

@Override

public List<Menu> getMonthMenu (final int year, final int month) {


엄청 쉽게 적용하며 DB의 요청을 줄일수 있다.!!