본문 바로가기

Spring Boot

[Spring Boot] Redis 설명 및 예제

728x90

개요

Redis는 키-값 구조의 데이터 저장소로, 데이터의 빠른 액세스가 필요한 애플리케이션에서 주로 사용됩니다. Spring Boot에서는 Redis를 손쉽게 통합하여 캐시, 세션 관리, 실시간 데이터 처리를 구현할 수 있습니다.

 

오픈 소스, 인메모리 데이터 저장소로, 주로 캐싱, 세션 저장소, 메시지 브로커로 사용됩니다. 모든 데이터를 메모리에 저장하므로 매우 빠른 속도로 데이터를 읽고 쓸 수 있으며, 다양한 데이터 구조(리스트, 셋, 해시 등)를 지원합니다.

 

주요 특징:

  • 인메모리 데이터베이스: 데이터가 메모리에 저장되어 초고속 접근이 가능합니다.
  • 다양한 데이터 구조 지원: 단순한 키-값뿐만 아니라, 리스트, 셋, 해시, 정렬된 셋 등 다양한 구조를 지원합니다.
  • 영속성 옵션: 데이터의 영속성을 위해 디스크에 주기적으로 데이터를 저장할 수 있습니다.

 

Spring Boot에서 Redis 사용 구조

Spring Boot는 Redis와의 통합을 위해 spring-boot-starter-data-redis 스타터를 제공합니다. 이를 통해 Redis와의 연결, 데이터 접근, 캐시 관리 등의 기능을 쉽게 설정하고 사용할 수 있습니다.

 

구성 요소:

  • RedisTemplate: Redis와 상호작용하는 주요 인터페이스로, 다양한 Redis 명령을 실행할 수 있습니다.
  • StringRedisTemplate: 문자열 기반의 Redis 명령을 처리하기 위한 클래스입니다.
  • @Cacheable, @CachePut, @CacheEvict: 캐싱을 위한 애노테이션으로, 메서드의 결과를 Redis에 캐시하거나 캐시를 무효화할 수 있습니다.

Spring Boot에서 Redis 설정

1. 의존성 추가

먼저, Spring Boot 프로젝트에 Redis 관련 의존성을 추가합니다. build.gradle 파일에 다음과 같이 추가합니다:

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

 

Redis 서버에 연결하기 위한 설정을 application.yml 파일에 추가합니다:

spring:
  redis:
    host: localhost
    port: 6379

 

application.properties 파일을 사용할 경우:

spring.redis.host=localhost
spring.redis.port=6379

 

RedisTemplate 설정

 

RedisTemplate을 이용하여 Redis와 상호작용할 수 있습니다. 필요에 따라 사용자 정의 RedisTemplate 빈을 설정할 수 있습니다.

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

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer()); // 다른 Serializer로 교체 가능
        return template;
    }
}

 

 

RedisTemplate을 이용한 간단한 사용 예제

 

Redis에 데이터를 저장하고 가져오는 간단한 예제를 작성해 보겠습니다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void saveData(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public String getData(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    public void deleteData(String key) {
        redisTemplate.delete(key);
    }
}

 

이제, RedisService를 통해 데이터를 Redis에 저장하고 가져올 수 있습니다.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisService redisService;

    @GetMapping("/save")
    public String saveData(@RequestParam String key, @RequestParam String value) {
        redisService.saveData(key, value);
        return "Data saved";
    }

    @GetMapping("/get")
    public String getData(@RequestParam String key) {
        return redisService.getData(key);
    }

    @GetMapping("/delete")
    public String deleteData(@RequestParam String key) {
        redisService.deleteData(key);
        return "Data deleted";
    }
}

 

위 예제에서는 /redis/save, /redis/get, /redis/delete 엔드포인트를 통해 Redis에 데이터를 저장, 조회, 삭제할 수 있습니다.

 

캐시로 Redis 사용하기

Spring Boot에서 Redis를 캐시로 사용하려면, @EnableCaching 애노테이션을 사용하여 캐싱 기능을 활성화하고, 메서드에 @Cacheable, @CachePut, @CacheEvict 애노테이션을 추가합니다.

 

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

@Service
public class CacheService {

    @Cacheable(value = "items", key = "#id")
    public String getItem(String id) {
        // 데이터베이스나 외부 API 호출 (비용이 큰 작업)
        return "Item " + id;
    }
}

 

이제 getItem 메서드를 호출할 때, 첫 호출은 실제 메서드가 실행되지만, 이후 호출은 캐시된 결과를 반환합니다.

 

 

  • Redis 개념: Redis는 인메모리 데이터 저장소로, 빠른 데이터 액세스가 필요한 애플리케이션에서 사용됩니다.
  • Spring Boot 통합: Spring Boot에서 Redis는 spring-boot-starter-data-redis를 통해 쉽게 통합할 수 있습니다.
  • Redis 설정: application.yml 또는 application.properties에서 Redis 서버 정보를 설정하고, RedisTemplate을 통해 데이터를 저장, 조회, 삭제할 수 있습니다.
  • 캐시로 사용: Spring Boot에서 Redis를 캐시로 활용할 수 있으며, 이를 통해 애플리케이션 성능을 개선할 수 있습니다.