티스토리 뷰

Spring

Spring boot 2.x + ehcache 3.x

§무명소졸§ 2020. 1. 30. 09:33

웹 애플리케이션에서 사용자 요청에 대한 빠른 응답 속도 개선을 위해 client browser cache 나 server에 메모리등을 이용한 cache를 활용할 수 있다. 오늘은 spring boot2.x 와 연동할 수 있는 무료 오픈소스 cache framework인 ehcache를 활용하는 방법을 알아보겠다.

pom.xml

spring boot 와 ehcache 연동을 위한 필수적인 maven dependency 목록이다. 

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
	<groupId>javax.cache</groupId>
	<artifactId>cache-api</artifactId>
</dependency>
<dependency>
	<groupId>org.ehcache</groupId>
	<artifactId>ehcache</artifactId>
	<version>3.6.2</version>
</dependency>
   

@EnableCaching

cache 메소드들의 proxy 메서드를 만들기 위한 annotation이다. 반드시 선언해야 한다. 예제는 소스를 간단하게 하기위해서 spring boot main 클래스에 선언했지만 별도의 cache configuration java 파일을 구성하는 것도 괜찮다.

@SpringBootApplication
@EnableCaching
public class EhcachetestApplication {

    public static void main(String[] args) {
        SpringApplication.run(EhcachetestApplication.class, args);
    }

}

ehcache.xml 

ehcache의 설정정보를 담고 있는 xml 파일이다. 

  • <cache alias="cache_names"> :  cache 의 이름이다.
  • <key-type>: cache 내부의 entry 들을 구분할 수 있는 key 의 type 이다.
  • <value-type>: cache 에 저장된 entry 들의 type 이다.
  • <expiry>: cache 만료에 관한 설정이다. <ttl unit="minutes">1</ttl> cache 안에서 생성된지 1분이 지난 entry는 삭제된다.
  • <resources>: cache의 메모리나 디스크 사용등 자원에 대한 설정이다. <heap unit="entries">2</heap> heap 메모리를 사용하고 최대 2개의 entry 만 cache 저정한다. 즉 3번째 entry가 생성할 경우 기존의 entry를 삭제한다. 삭제 대상은 별도 설정을 하지 않으면 default 전략인 LRU(Least Recently Used)을 사용한다.
<config
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns='http://www.ehcache.org/v3'
        xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">
    <cache alias="cache_names">
        <key-type>java.lang.String</key-type>
        <value-type>java.util.List</value-type>
        <expiry>
            <ttl unit="minutes">1</ttl>
        </expiry>
        <resources>
            <heap unit="entries">2</heap>
        </resources>
    </cache>
</config>

application.properties

spring boot 설정 정보에 ehcache.xml 파일을 명시적으로 선언한다. 

spring.cache.jcache.config=classpath:ehcache.xml

NameResource

cache API 테스트를 위한 Restful Controller 이다. path variable 변수를 전달 받는다.

package info.m2sj.ehcachetest;

import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api")
@AllArgsConstructor
public class NameResource {
    private final NameService nameService;

    @GetMapping("/names/{prefix}")
    public List<String> getName(@PathVariable String prefix) {
       return nameService.findNames(prefix);
    }
}

NameService

실제 caching 되는 메서드를 포함하고 있는 서비스이다. 입력 받은 메소드 인자를 접두사로 500개의 랜덤 문자열을 리스트에
담아 반환한다. @Cacheable(value = "cache_names", key = "#prefix") 이 부분이 해당 메서드를 cache를 적용한다는 의미이다. value="cache_names" 부분이 ehcache.xml 에서 설정한  alias 이고  key = "#prefix" 부분은 메서드 파라메터를 key로 사용한다는 의미이다.

package info.m2sj.ehcachetest;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class NameService {

    @Cacheable(value = "cache_names", key = "#prefix")
    public List<String> findNames(String prefix) {
       log.info("====== Start Generating name ======");
       List<String> rtnList = new ArrayList<>();

       for (int i = 0; i < 500; i++) {
           rtnList.add(prefix + "_" + RandomStringUtils.randomAlphabetic(5));
       }
       log.info("====== Completed ======");
       return rtnList;
    }
}

Test

애플리케이션을 Startup 하고 아래 URI 호출하면 aaa_ 가 포함된 랜덤 문자열 리스트를 확인할 수 있다.
http://localhost:8080/api/names/aaa

- 결과

처음에는 메서드를 통해 처리됐기 때문에 아래와 같이 출력 was 로그를 확인할 수 있다.

다시 한번 http://localhost:8080/api/names/aaa 호출하면 로그가 출력되지 않는다. 즉 메서드를 통하지 않고 cache에 올라가 있는 데이터를 조회한다. 1분후 다시 조회하면 다시 로그가 출력된다. ehcache.xml 에서 <ttl unit="minute">1</ttl> 설정 때문이다. http://localhost:8080/api/names/bbb, http://localhost:8080/api/names/ccc
등 다른 URI를 조회해서 cache entry를 증가시키거나  ehcache.xml 에 옵션을 변경하면서 cache의 동작이 어떻게 변경되는지 확인해보자.

기타

spring boot 2. 와 ehcache3 를 연동해서 가장 기본적인 사용법과 테스트를 해봤다. 예제의 전체 소스와 ehcache에 대한 더 많은 정보는 아래 링크를 참고하면된다.

'Spring' 카테고리의 다른 글

static resources in spring boot  (0) 2020.07.11
Spring Security (Spring Boot) #4  (0) 2020.02.28
Spring Security (Spring Boot) #3 form login customize  (0) 2020.01.20
Spring Security (Spring Boot) #2  (0) 2020.01.10
Spring Security (Spring Boot) #1  (0) 2020.01.03
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크