Spring Boot 프로젝트에 Redisson 도입하기: YAML 및 Java Config 기반 연동 가이드

Redis와 Redisson의 차이점

Redis는 문자열, 해시, 리스트 등 다양한 자료구조를 지원하는 오픈소스 인메모리 데이터베이스입니다. 주로 캐싱, 분산 락, 메시지 큐 등으로 활용됩니다. 반면 Redisson은 Redis를 기반으로 구축된 Java 인메모리 데이터 그리드(In-Memory Data Grid)입니다. 분산 환경에서 사용되는 Java 객체, 다양한 락 메커니즘, 동기화 도구 등을 제공하여 개발자가 인프라보다는 비즈니스 로직에 집중할 수 있도록 돕습니다.

환경 준비

본 가이드에서는 Spring Boot와 Redisson Starter를 사용합니다.

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.21.1</version>
</dependency>

연동 방식 1: YAML 파일을 활용한 설정

가장 직관적인 방법으로, Spring Boot의 기본 설정 파일이나 Redisson 전용 설정 파일을 사용합니다.

1. 단일 노드 (Single Node)

기존 Spring Data Redis 설정을 그대로 확장하거나, 별도의 redisson-config.yml을 참조할 수 있습니다.

application.yml

spring:
  redis:
    redisson:
      file: classpath:redisson-config.yml

redisson-config.yml

singleServerConfig:
  database: 0
  address: "redis://127.0.0.1:6379"
  password: "my_secure_password"

2. 클러스터 (Cluster)

클러스터 환경에서는 여러 노드의 주소를 명시해야 하며, Redis 클러스터 특성상 데이터베이스 인덱스(database) 파라미터는 사용하지 않습니다.

redisson-config.yml

clusterServersConfig:
  nodeAddresses:
    - "redis://127.0.0.1:7000"
    - "redis://127.0.0.1:7001"
    - "redis://127.0.0.1:7002"
  password: "my_secure_password"

연동 방식 2: Java Configuration 클래스를 통한 동적 설정

YAML 파일 분리 없이 application.yml의 커스텀 프로퍼티를 읽어 Java 코드로 RedissonClient 빈을 직접 등록하는 방식입니다. 단일 노드, 클러스터, 센티널, 마스터-슬레이브 모드를 모두 포괄하도록 구현했습니다.

application.yml

custom:
  redisson:
    active: true
    deployment-mode: single # single, cluster, sentinel, master-slave
    endpoints: redis://127.0.0.1:6379
    credential: my_secure_password
    db-index: 0
    sentinel-master: mymaster

RedissonClientConfiguration.java

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Configuration
@ConditionalOnProperty(prefix = "custom.redisson", name = "active", havingValue = "true")
public class RedissonClientConfiguration {

    @Value("${custom.redisson.deployment-mode}")
    private String deploymentMode;

    @Value("${custom.redisson.endpoints}")
    private String endpoints;

    @Value("${custom.redisson.credential:}")
    private String credential;

    @Value("${custom.redisson.db-index:0}")
    private int dbIndex;

    @Value("${custom.redisson.sentinel-master:}")
    private String sentinelMaster;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient buildRedissonClient() {
        Config configuration = new Config();
        String[] nodes = endpoints.split(",");
        
        if (credential != null && credential.trim().isEmpty()) {
            credential = null;
        }

        switch (deploymentMode.toLowerCase()) {
            case "single":
                configuration.useSingleServerConfig()
                        .setAddress(nodes[0])
                        .setPassword(credential)
                        .setDatabase(dbIndex);
                break;
            case "cluster":
                configuration.useClusterServers()
                        .addNodeAddress(nodes)
                        .setPassword(credential);
                break;
            case "sentinel":
                configuration.useSentinelServersConfig()
                        .setMasterName(sentinelMaster)
                        .addSentinelAddress(nodes)
                        .setPassword(credential)
                        .setDatabase(dbIndex);
                break;
            case "master-slave":
                if (nodes.length < 2) {
                    throw new IllegalStateException("Master-slave mode requires at least one master and one slave node.");
                }
                String masterNode = nodes[0];
                String[] slaveNodes = Arrays.copyOfRange(nodes, 1, nodes.length);
                configuration.useMasterSlaveServers()
                        .setMasterAddress(masterNode)
                        .addSlaveAddress(slaveNodes)
                        .setPassword(credential)
                        .setDatabase(dbIndex);
                break;
            default:
                throw new UnsupportedOperationException("Unsupported deployment mode: " + deploymentMode);
        }

        return Redisson.create(configuration);
    }
}

태그: SpringBoot Redisson Redis JavaConfig YAML

7월 11일 22:21에 게시됨