티스토리 뷰

이번 포스팅은 Spring에서 Redis 연동하는 방법입니다. SpringBoot 3.1.5 기준으로 작성되었습니다.


1. 라이브러리 추가

  • build.gradle redis 추가
implementation 'org.springframework.boot:spring-boot-starter-data-redis:3.1.5'



2. 설정값 작성

  • application.yml redis 설정값 추가
spring:
  config:
    activate:
      on-profile: "local"

  data:
    redis:
      port: 6379
      host: 127.0.0.1
      password: admin



3. RedisConfig 작성

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
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 {

  @Value("${spring.data.redis.host}")
  private String redisHost;

  @Value("${spring.data.redis.port}")
  private String redisPort;

  @Value("${spring.data.redis.password}")
  private String redisPassword;

  @Bean
  public RedisConnectionFactory redisConnectionFactory() {
    RedisStandaloneConfiguration redisStandaloneConfiguration = 
    	new RedisStandaloneConfiguration();
        
    redisStandaloneConfiguration.setHostName(redisHost);
    redisStandaloneConfiguration.setPort(Integer.parseInt(redisPort));
    redisStandaloneConfiguration.setPassword(redisPassword);
    
    LettuceConnectionFactory lettuceConnectionFactory = 
    	new LettuceConnectionFactory(redisStandaloneConfiguration);
        
    return lettuceConnectionFactory;
  }

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

}



4. RedisService 작성

import com.google.gson.JsonObject;
import com.myapi.mymsgapi.comm.utils.ObjectUtil;
import com.myapi.mymsgapi.comm.utils.StringUtil;
import com.myapi.mymsgapi.dao.room.RoomDAO;
import com.myapi.mymsgapi.model.ChatMessage;
import com.myapi.mymsgapi.model.UserRoomInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class RedisService {

  private final RedisTemplate<String, String> _redisTemplate;

  /**
   * redis set
   */
  private void set(final String key, final String value, final boolean isOverride) {
    ValueOperations<String, String> vop = _redisTemplate.opsForValue();

    if (isOverride) {
      vop.set(key, value);
    } else {
      String result = vop.get(key);
      if (result != null && StringUtil.isNotEmpty(result)) {
        // TODO : append ?
      } else {
        vop.set(key, value);
      }
    }
  }

  /**
   * redis list append
   */
  private void appendToList(final String key, final String value) {
    ListOperations<String, String> lop = _redisTemplate.opsForList();
    lop.rightPush(key, value);
  }

  /**
   * redis get value
   */
  private String getValue(final String key) {
    ValueOperations<String, String> vop = _redisTemplate.opsForValue();
    String value = vop.get(key);
    return value;
  }

  private List<Object> getHashValue(final String key) {
    return _redisTemplate.opsForHash().values(key);
  }

  /**
   * redis get list
   */
  private List<String> getList(final String key) {
    return _redisTemplate.opsForList().range(key, 0, -1);
  }

  /**
   * redis get list last data
   */
  private JsonObject getLast(final String key) {
    List<String> values = _redisTemplate.opsForList().range(key, -1, -1);
    return (values != null && !values.isEmpty()) ? ObjectUtil.toJson(values.get(0)) : null;
  }

  /**
   * redis get hash value(JSONObject)
   */
  private JsonObject getJson(final String key, final String group) {
    return (JsonObject) _redisTemplate.opsForHash().get(key, group);
  }

  /**
   * redis set hash
   */
  private void setHash(final String key, final String group, final String value) {
    _redisTemplate.opsForHash().put(key, group, value);
  }

  /**
   * redis delete hash group
   */
  private void deleteHashGroup(final String key, final String group) {
    _redisTemplate.opsForHash().delete(key, group);
  }

  /**
   * redis delete hash key
   */
  private void deleteHashKey(final String key) {
    _redisTemplate.opsForHash().delete(key);
  }

}



감사합니다.

최근에 올라온 글
Total
Today
Yesterday