새벽코딩

[Spring Legacy] + Redis Cache (공통 코드, 메시지) 관리 본문

Spring/Spring Legacy

[Spring Legacy] + Redis Cache (공통 코드, 메시지) 관리

J 코딩 2024. 1. 22. 14:46
반응형

Spring Boot가 아닌 Spring Legacy 환경에서의 Redis Cache 연동 및 공통코드, 메시지를 관리해보자.

전체환경

[java]

  • jdk : 1.8

[apache-tomcat]

  • apache-tomcat : 9.0.44

[spring]

  • spring-core : 5.1.5.RELEASE
  • spring-webmvc : 5.1.5.RELEASE
  • spring-context : 5.1.5.RELEASE
  • spring-tx : 5.1.5.RELEASE
  • spring-aop : 5.1.5.RELEASE

[redis]

  • spring-data-redis : 2.2.1.RELEASE
  • lettuce-core : 6.0.2.RELEASE

Redis.config

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    @Value("${spring.redis.host}")
    String redisHost;

    @Value("${spring.redis.port}")
    int redisPort;

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

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

@Value("${spring.redis.host}")
@Value("${spring.redis.port}")
properties파일에 변수를 담아두고 @Value 어노테이션을 사용해 값을 꺼내서 사용한다

[Redis Connection] - LettuceConnection

https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/connection/lettuce/LettuceConnection.html

While the underlying Lettuce RedisClient and StatefulRedisConnection instances used by LettuceConnection are Thread-safe, this class itself is not Thread-safe. Therefore, instances of LettuceConnection should not be shared across multiple Threads when executing Redis commands and other operations. If optimal performance is required by your application(s), then we recommend direct access to the low-level, API provided by the underlying Lettuce client library (driver), where such Thread-safety guarantees can be made. Simply call getNativeConnection() and use the native resource as required.

본 시스템에서는 싱글 스레드기반의 레디스 커넥션을 유지할 예정이므로 LettuceConnection을 사용하여도 무방하다.

[RedisTemplate<String, Object>]

Bean 주입을 통해 여러 파일에서 사용가능하도록 해준다. 이때 직렬화 정보를 담아줄 수 있다.
KeySerializer(new StringRedisSerializer()) 으로 스트링 기반의 Key값을 받도록 해준다.
ValueSerializer(new GenericJackson2JsonRedisSerializer()) 으로 Json기반의 Value값을 받도록 해준다.

여기선 Value에 대량의 코드정보를 담아서 시스템에서 사용하도록 해야한다.


CacheService.java

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    private List<LinkedHashMap> getCcCodes ()
    {
        List<LinkedHashMap> dtCode = new List<LinkedHashMap>();

        try {
            dtCode = getCodeFromRedis(CacheCodeConstants.COMMON_CODE_LIST);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dtCode;
    }

    private List<LinkedHashMap> getMcCodes ()
    {
        List<LinkedHashMap> dtCode = new List<LinkedHashMap>();

        try {
            dtCode = getCodeFromRedis(CacheCodeConstants.MESSAGE_CODE_LIST);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dtCode;
    }

    private List<LinkedHashMap> getCodeFromRedis(String cKey) throws Exception {
        // return값을 담을 데이터테이블
        List<LinkedHashMap> dtCode = new List<LinkedHashMap>();        
        String key = cKey;

        // Redis에 키가 있는 경우 조회한다
        if(key != null && redisTemplate.hasKey(key)) {
            // redis에서 값을 추출한다
            String extractCache = redisTemplate.opsForValue().get(key).toString();

            // 원하는 모양으로 파싱한다
            dtCode = parseStringToMap(extractCache);
        }
        else 
        {
            Map<String, Object> param = new LinkedHashMap<String, Object>();
            param("PARAM", "DATA");

            // DB에서 공통코드 데이터 조회
            switch (key) {
            case CacheCodeConstants.COMMON_CODE_LIST:
                dtCode = cachesDao.getCommonCodes(param);
                break;
            case CacheCodeConstants.MESSAGE_CODE_LIST:
                dtCode = cachesDao.getMessages(param);
                break;
            default:
                break;
            }

            // DataTable을 jsonData로 변형한다
            String jsonData = parseJsonToString(dtCode);

            // Redis에 값을 적재한다 (JSON)
            redisTemplate.opsForValue().set(key, jsonData);
        }

        return dtCode;
    }
  1. if(key != null && redisTemplate.hasKey(key))

저장하려는 키가 존재하는지 확인한다.

이상입니다.

반응형
Comments