IT Developer/Spring

Spring 기초 <14. Spring Boot에서 Redis를 활용한 캐싱(Cache) 전략>

TEMA_ 2025. 3. 31. 13:35
반응형

스프링 Spring

14. Spring Boot에서 Redis를 활용한 캐싱(Cache) 전략

 

안녕하세요! 태마입니다.

Spring 기초 강좌입니다.

 

강좌의 경우 

1. 주제 간단 정리

2. 상세 주제 정리

으로 이루어져 있습니다.

 

스프링 Spring

포스팅 시작하겠습니다 :)

 


 

1. 주제 간단 정리

1. Redis란?

Redis(Remote Dictionary Server)는 In-Memory(메모리 기반) 데이터 저장소로, 빠른 속도를 제공하는 NoSQL 데이터베이스
주로 캐싱(Cache), 세션 저장(Session Store), 메시지 브로커(Message Broker) 등으로 활용됨

📌 Redis의 주요 특징

특징설명
In-Memory 데이터 저장 모든 데이터를 메모리에 저장하여 빠른 속도로 데이터 접근 가능
Key-Value 기반 저장 키(Key)와 값(Value) 형태로 데이터를 저장
다양한 데이터 구조 지원 String, List, Set, Hash, Sorted Set 등 다양한 자료형 지원
자동 만료(Expiration) 기능 TTL(Time-To-Live)을 설정하여 자동으로 데이터 삭제 가능
트랜잭션 및 퍼시스턴스 지원 데이터 손실을 방지하는 AOF(Append Only File) 및 RDB(Snapshot) 기능 제공

📌 Redis는 "빠른 데이터 접근이 필요한 환경에서 캐싱 솔루션으로 사용됨"


2. Spring Boot에서 캐싱(Cache)이 필요한 이유

데이터베이스 조회는 비용이 크고, 요청이 많아질수록 성능 저하 발생 가능
자주 사용되는 데이터를 Redis에 캐싱하면 성능을 개선하고 데이터베이스 부하를 줄일 수 있음

📌 Spring Boot에서 캐싱이 필요한 경우
자주 조회되는 데이터 (예: 상품 목록, 인기 게시글 등)
동일한 요청이 반복적으로 발생하는 경우
데이터베이스 부하를 줄이고 응답 속도를 빠르게 하고 싶을 때

📌 Redis를 사용하면 "데이터베이스 요청을 줄이고 애플리케이션 성능을 극대화 가능"


✅ 여기까지 Redis의 개념과 캐싱의 필요성을 배웠습니다!
👉 "그렇다면, Spring Boot에서 Redis를 어떻게 설정할까?"
✅ 2부에서 Spring Boot에서 Redis 설정 및 캐싱 구현 방법을 배워봅시다!

반응형

 

2. 상세 주제 정리

 

1. Redis 의존성 추가

Spring Boot 프로젝트에 Redis를 사용하려면 spring-boot-starter-data-redis 의존성을 추가해야 함

📌 1️⃣ build.gradle 설정

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
}

Spring Data Redis를 추가하면 자동으로 Redis와 연결 가능


2. Redis 설정 (application.properties)

Redis 서버 정보를 설정하여 Spring Boot와 Redis를 연결

📌 application.properties

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.timeout=6000
spring.redis.password=

기본적으로 localhost:6379에서 Redis 서버와 연결

📌 Spring Boot는 "자동으로 Redis와 연결되며, 캐싱 기능을 쉽게 사용할 수 있음"


3. Redis 연결 테스트 (Configuration 설정)

RedisTemplate을 사용하여 Redis와의 연결을 확인할 수 있음

📌 RedisConfig 설정

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }
}

LettuceConnectionFactory를 사용하여 Redis에 연결
RedisTemplate을 통해 데이터를 저장하고 조회 가능

📌 RedisTemplate을 사용하면 "Redis와 쉽게 데이터를 주고받을 수 있음"


4. @Cacheable을 활용한 캐싱 적용

Spring Boot에서는 @Cacheable을 사용하여 간단하게 캐싱 적용 가능

📌 UserService에 캐싱 적용

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

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    private static final Map<Long, String> database = new HashMap<>();

    static {
        database.put(1L, "John Doe");
        database.put(2L, "Jane Smith");
    }

    @Cacheable(value = "user", key = "#id")
    public String getUser(Long id) {
        System.out.println("데이터베이스에서 조회...");
        return database.get(id);
    }
}

@Cacheable(value = "user", key = "#id")를 사용하면 Redis에 캐싱됨
한 번 조회한 데이터는 Redis에서 가져오기 때문에 데이터베이스 부하가 줄어듦

📌 @Cacheable을 사용하면 "자동으로 Redis에 캐싱되어 성능을 최적화할 수 있음"


5. 캐싱된 데이터 삭제 (@CacheEvict)

데이터가 변경될 경우, 기존 캐시를 삭제하여 최신 데이터를 반영해야 함

📌 캐시 삭제 설정

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

@Service
public class UserService {

    private static final Map<Long, String> database = new HashMap<>();

    static {
        database.put(1L, "John Doe");
        database.put(2L, "Jane Smith");
    }

    @Cacheable(value = "user", key = "#id")
    public String getUser(Long id) {
        System.out.println("데이터베이스에서 조회...");
        return database.get(id);
    }

    @CacheEvict(value = "user", key = "#id")
    public void updateUser(Long id, String name) {
        database.put(id, name);
    }
}

데이터가 변경될 때 @CacheEvict를 사용하여 캐시를 삭제

📌 @CacheEvict를 사용하면 "최신 데이터를 유지하면서 캐싱을 효율적으로 관리 가능"


6. 캐싱된 데이터 확인 (Redis CLI 사용)

Redis에 데이터가 캐싱되었는지 확인하려면 Redis CLI를 사용 가능

📌 Redis CLI에서 데이터 조회

$ redis-cli
127.0.0.1:6379> KEYS *
"user::1"

키(user::1)가 생성되었으면 캐싱 성공

📌 Redis는 "캐싱된 데이터를 빠르게 조회할 수 있어 성능을 극대화 가능"


✅ 여기까지 Spring Boot에서 Redis를 활용한 캐싱 전략을 배웠습니다!
👉 "그렇다면, Spring Batch를 활용하여 대용량 데이터 처리는 어떻게 할까?"
✅ 다음 회차에서 Spring Batch – 대용량 데이터 처리 및 배치 작업 구현을 배워봅시다!



 

반응형