포스트

Spring Boot - Redis 설정

적용 환경

  • Spring Boot 3.2.0


Redis는 NoSQL 데이터베이스로 간단한 형태의 키에 데이터를 저장하는 키-값 저장소이다.

데이터 캐싱, 세션 관리, 실시간 분석, 대기열 처리 등 빠른 응답이 필요한 프로그램에서 사용한다고 한다!

Redis를 Spring Boot에서 사용할 수 있도록 설정하는 방법을 정리 ✏️




의존성 추가

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


application.yml 설정 추가

만약 redis의 데이터베이스를 여러 개 사용하는 경우라면 database 옵션 설정을 꼭 해주도록 한다.
만약 database도 port도 host도 기본 설정(0, 6379, localhost)를 사용한다면 추가 설정을 하지 않아도 된다.
기본 값을 사용하다가 언젠가 바뀔 가능성이 있다면 처음부터 설정을 작성해 두는 것이 좋을 것 같아서 나의 경우 처음부터 설정을 작성해두고 시작하는 편이다!

1
2
3
4
5
6
spring:
  data:  
    redis:  
      host: localhost  
      port: 6379  
      database: 0


RedisConfig 설정으로 bean 생성

내 경우 개인 프로젝트에서 사용 할 때 테스트에서는 사용하는 데이터베이스 인덱스와 운영 환경에서 실행하는 데이터베이스 인덱스 만 구분하여 같은 접속지의 Redis를 테스트 환경과 운영 환경에서 공유하도록 설정하고 사용하고 있어서 database 옵션을 추가해주었다.

database 옵션을 추가하려면 RedisStandaloneConfiguration을 구현하여 설정을 적용해 주면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Configuration  
public class RedisConfig {  
    @Value("${spring.data.redis.host}")  
    private String host;  
      
    @Value("${spring.data.redis.port}")  
    private int port;  
      
    @Value("${spring.data.redis.database}")  
    private int dbIndex;  
      
      
      
    @Bean  
    public RedisConnectionFactory redisConnectionFactory() {  
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();  
        redisStandaloneConfiguration.setHostName(host);  
        redisStandaloneConfiguration.setPort(port);  
        redisStandaloneConfiguration.setDatabase(dbIndex);  
          
        return new LettuceConnectionFactory(redisStandaloneConfiguration);  
    }  
}


그리고 Hash 와 Set 등 Redis의 자료구조를 쉽게 사용할 수 있도록 해주는 RedisTemplate 관련 설정도 함께 작성해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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());  
        template.setHashKeySerializer(new StringRedisSerializer());  
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());  
        return template;  
    }  
}




참고한 사이트

  • https://velog.io/@kenux/SpringBootRedis1
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.