1. 개요

Spring Boot와 함께 Ehcache를 사용하는 예를 살펴 보겠습니다. JSR-107 캐시 관리자 의 구현을 제공하므로 Ehcache 버전 3을 사용할 것 입니다.

이 예는 숫자의 제곱을 생성하는 간단한 REST 서비스입니다.

2. 의존성

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.4.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.4.0</version></dependency>
<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.8.1</version>
</dependency>     

3. 예

서비스를 호출하여 숫자를 제곱하고 결과를 JSON 문자열로 반환하는 간단한 REST 컨트롤러를 만들어 보겠습니다.

@RestController
@RequestMapping("/number", MediaType.APPLICATION_JSON_UTF8_VALUE)
public class NumberController {

    // ...

    @Autowired
    private NumberService numberService;

    @GetMapping(path = "/square/{number}")
    public String getSquare(@PathVariable Long number) {
        log.info("call numberService to square {}", number);
        return String.format("{\"square\": %s}", numberService.square(number));
    }
}

이제 서비스를 만들어 보겠습니다.

Spring이 캐싱을 처리 할 수 ​​있도록 @Cacheable로 메서드에 어노테이션을 답니다 . 이 어노테이션의 결과로 Spring은 square 메서드 에 대한 호출을 가로 채고 Ehcache를 호출하기 위해 NumberService 의 프록시를 생성합니다 .

사용할 캐시의 이름과 선택적으로 키를 제공해야합니다. 캐싱되는 것을 제한하는 조건을 추가 할 수도 있습니다.

@Service
public class NumberService {

    // ...
    @Cacheable(
      value = "squareCache", 
      key = "#number", 
      condition = "#number>10")
    public BigDecimal square(Long number) {
        BigDecimal square = BigDecimal.valueOf(number)
          .multiply(BigDecimal.valueOf(number));
        log.info("square of {} is {}", number, square);
        return square;
    }
}

마지막으로 메인 Spring Boot 애플리케이션을 만들어 보겠습니다.

@SpringBootApplication
public class Application {

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

4. 캐시 구성

Spring의 어노테이션 기반 캐시 관리가 활성화되도록 Spring의 @EnableCaching 어노테이션을 Spring Bean 에 추가해야합니다 .

CacheConfig 클래스를 만들어 보겠습니다 .

@Configuration
@EnableCaching
public class CacheConfig {
}

Spring의 자동 구성은 Ehcache의 JSR-107 구현을 찾습니다. 그러나 기본적으로 캐시는 생성되지 않습니다.

Spring도 Ehcache도 기본 ehcache.xml 파일을 찾지 않기 때문 입니다. 다음 속성을 추가하여 Spring을 찾을 위치를 알려줍니다.

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

squareCache 라는 캐시가 있는 ehcache.xml 파일을 만들어 보겠습니다 .

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.ehcache.org/v3"
    xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
    xsi:schemaLocation="
            http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
            http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

    <cache alias="squareCache">
        <key-type>java.lang.Long</key-type>
        <value-type>java.math.BigDecimal</value-type>
        <expiry>
            <ttl unit="seconds">30</ttl>
        </expiry>

        <listeners>
            <listener>
                <class>com.baeldung.cachetest.config.CacheEventLogger</class>
                <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
                <event-ordering-mode>UNORDERED</event-ordering-mode>
                <events-to-fire-on>CREATED</events-to-fire-on>
                <events-to-fire-on>EXPIRED</events-to-fire-on>
            </listener>
        </listeners>

        <resources>
            <heap unit="entries">2</heap>
            <offheap unit="MB">10</offheap>
        </resources>
    </cache>

</config>

또한 CREATEDEXPIRED 캐시 이벤트를 모두 기록하는 캐시 이벤트 리스너도 추가해 보겠습니다 .

public class CacheEventLogger 
  implements CacheEventListener<Object, Object> {

    // ...

    @Override
    public void onEvent(
      CacheEvent<? extends Object, ? extends Object> cacheEvent) {
        log.info(/* message */,
          cacheEvent.getKey(), cacheEvent.getOldValue(), cacheEvent.getNewValue());
    }
}

5. 행동

mvn spring-boot : run 을 실행하여 Maven을 사용하여이 앱을 시작할 수 있습니다 .

그런 다음 브라우저를 열고 포트 8080에서 REST 서비스에 액세스하십시오.

우리가 가면  통해 http : // localhost : 8080 / 수 / 평방 / 12 우리는 다시 얻을 것이다 : {144 "광장"} , 및 로그에 우리는 볼 수 있습니다 :

INFO [nio-8080-exec-1] c.b.cachetest.rest.NumberController : call numberService to square 12
INFO [nio-8080-exec-1] c.b.cachetest.service.NumberService : square of 12 is 144
INFO [e [_default_]-0] c.b.cachetest.config.CacheEventLogger : Cache event CREATED for item with key 12. Old value = null, New value = 144

우리는에서 로그 메시지를 볼 수있는 광장 의 방법 NumberService 하고 CREATED EventLogger에서 이벤트입니다. 그런 다음 브라우저를 새로 고치면 로그에 다음 항목 만 추가됩니다.

INFO [nio-8080-exec-2] c.b.cachetest.rest.NumberController : call numberService to square 12

NumberServicesquare 메서드 에있는 로그 메시지 가 호출되지 않습니다. 이것은 캐시 된 값이 사용되고 있음을 보여줍니다.

캐시 된 항목이 만료 될 때까지 30 초를 기다렸다가 브라우저를 새로 고치면 EXPIRED 이벤트가 표시 되고 값이 캐시에 다시 추가됩니다.

INFO [nio-8080-exec-1] (...) NumberController : call numberService to square 12
INFO [e [_default_]-1] (...) CacheEventLogger : Cache event EXPIRED for item with key 12. Old value = 144,New value = null
INFO [nio-8080-exec-1] (... )NumberService : square of 12 is 144
INFO [e [_default_]-1] (...) CacheEventLogger : Cache event CREATED for item with key 12. Old value = null, New value = 144

우리가 입력하는 경우 에 http : // localhost를 : / 3 평방 8080 / 수 / 브라우저에, 우리는 9의 정확한 답변을 얻을, 값이 캐시되지 않습니다.

이는 @Cacheable 어노테이션에서 10보다 큰 숫자의 값만 캐시하기 위해 사용한 조건 때문입니다 .

6. 결론

이 빠른 자습서에서는 Spring Boot로 Ehcache를 설정하는 방법을 보여주었습니다.

항상 그렇듯이 코드 는 GitHub에서 찾을 수 있습니다 .