본문 바로가기

Spring

효율적인 캐싱 전략: Spring Cache의 기본 개념과 데이터 흐름 살펴보기

728x90
반응형

Spring Cache의 개념과 컨셉

Spring Cache는 애플리케이션에서 자주 조회되는 데이터를 캐싱하여 성능을 최적화하는 기능을 제공합니다. Spring에서는 캐시 추상화를 통해 다양한 캐시 제공자(e.g., EhCache, Caffeine, Redis 등)를 손쉽게 통합할 수 있습니다. Spring Cache는 주요 애너테이션 기반으로 작동하며, 메서드 호출 결과를 캐시에 저장하고, 이후 동일한 파라미터로 메서드를 호출할 때 캐시된 결과를 반환하여 메서드 실행을 생략할 수 있습니다.

Spring Cache의 주요 애너테이션

  1. @Cacheable: 이 애너테이션은 메서드의 실행 결과를 캐시에 저장합니다. 동일한 파라미터로 메서드가 다시 호출되면 캐시된 값을 반환합니다.
  2. @CachePut: 이 애너테이션은 메서드의 실행 결과를 항상 캐시에 저장하지만, 메서드는 실제로 실행됩니다. 주로 캐시를 갱신하는 데 사용됩니다.
  3. @CacheEvict: 이 애너테이션은 캐시에 저장된 데이터를 제거할 때 사용됩니다.
  4. @Caching: 여러 캐시 작업을 한 메서드에 결합하여 사용할 수 있습니다.

Spring Cache의 장점

  1. 성능 향상: 자주 호출되는 데이터나 시간이 많이 소요되는 연산 결과를 캐시함으로써 애플리케이션의 응답 속도를 대폭 향상시킬 수 있습니다. DB 조회나 복잡한 연산을 반복하지 않으므로 시스템 부하를 줄일 수 있습니다.
  2. 개발 생산성 향상: 캐싱을 간편하게 설정할 수 있는 애너테이션 기반의 방식은 개발자가 적은 코드로 쉽게 캐싱 기능을 추가할 수 있게 합니다. 특히 Spring의 다양한 캐시 제공자를 추상화해 놓은 덕분에, 특정 캐시 라이브러리에 종속되지 않고 필요한 경우 간편하게 교체할 수 있습니다.
  3. 유연한 캐시 관리: 캐시 키, 캐시 조건, 만료 시간 등을 쉽게 설정할 수 있어 복잡한 캐시 요구 사항도 유연하게 대응할 수 있습니다.

Spring Cache는 애플리케이션의 성능을 크게 향상시키고 개발 생산성을 높이는 데 매우 유용한 도구입니다. 그러나 캐시를 사용할 때는 데이터 일관성, 메모리 사용, 캐시 장애 등 다양한 측면을 고려해야 하며, 캐시 설정이 적절한지 주기적으로 검토하는 것이 중요합니다. 올바르게 활용하면, Spring Cache는 높은 성능의 애플리케이션을 구축하는 데 큰 도움이 됩니다.

반응형

Spring Cache를 EhCache 기반으로 구현하는 방법

프로젝트 설정

먼저, EhCache를 사용하기 위해 필요한 의존성을 추가합니다.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-cache'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.ehcache:ehcache:3.10.8'  // EhCache 라이브러리
}

EhCache 설정

EhCache 설정 파일인 ehcache.xml을 src/main/resources 디렉토리에 생성합니다. 이 파일에서는 캐시의 설정을 정의할 수 있습니다.

<?xml version="1.0" encoding="UTF-8"?>
<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="sampleCache">
        <key-type>java.lang.String</key-type>
        <value-type>java.lang.String</value-type>
        <expiry>
            <ttl unit="minutes">10</ttl>
        </expiry>
        <resources>
            <heap unit="entries">100</heap>
            <offheap unit="MB">10</offheap>
        </resources>
    </cache>

</config>

EhCache를 Spring Cache로 설정

Spring Boot에서 EhCache를 사용하려면 CacheManager를 설정해야 합니다. 이를 위해 캐시 설정을 Spring에 통합합니다.

import org.ehcache.jsr107.EhcacheCachingProvider;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.cache.Caching;
import javax.cache.spi.CachingProvider;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public JCacheCacheManager cacheManager() {
        CachingProvider provider = Caching.getCachingProvider(EhcacheCachingProvider.class.getName());
        javax.cache.CacheManager cacheManager = provider.getCacheManager(
            getClass().getResource("/ehcache.xml").toURI(),
            getClass().getClassLoader());

        return new JCacheCacheManager(cacheManager);
    }
}

서비스 레이어에서 캐싱 적용

이제 서비스 레이어에서 캐싱을 사용해봅니다. @Cacheable 애너테이션을 사용하여 메서드의 결과를 캐시에 저장합니다.

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class SampleService {

    private final SampleRepository sampleRepository;

    public SampleService(SampleRepository sampleRepository) {
        this.sampleRepository = sampleRepository;
    }

    @Cacheable(value = "sampleCache", key = "#name")
    public SampleEntity getSampleEntityByName(String name) {
        System.out.println("Fetching from database for name: " + name);
        return sampleRepository.findByName(name);
    }
}

 

728x90
반응형