Java로 Redis 조작하기: StringRedisTemplate 기반의 완벽한 Redis 유틸리티 클래스

ProtoStuff 직렬화/역직렬화 도구

다음은 ProtoStuff를 사용하여 객체와 리스트를 직렬화 및 역직렬화하는 유틸리티 클래스입니다.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;

public class CustomSerializerUtil {
    public static <T> byte[] serializeObject(T obj) {
        if (obj == null) throw new RuntimeException("객체가 null입니다.");
        var schema = RuntimeSchema.getSchema(obj.getClass());
        try (var bos = new ByteArrayOutputStream()) {
            ProtostuffIOUtil.writeTo(bos, obj, schema, LinkedBuffer.allocate(1024 * 1024));
            return bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("직렬화 중 오류 발생.", e);
        }
    }

    public static <T> T deserializeObject(byte[] data, Class<T> clazz) {
        if (data == null || data.length == 0) throw new RuntimeException("데이터가 비어 있습니다.");
        try {
            T instance = clazz.getDeclaredConstructor().newInstance();
            var schema = RuntimeSchema.getSchema(clazz);
            ProtostuffIOUtil.mergeFrom(data, instance, schema);
            return instance;
        } catch (Exception e) {
            throw new RuntimeException("역직렬화 중 오류 발생.", e);
        }
    }

    public static <T> byte[] serializeList(List<T> list) {
        if (list == null || list.isEmpty()) throw new RuntimeException("리스트가 비어 있습니다.");
        var schema = RuntimeSchema.getSchema(list.get(0).getClass());
        try (var bos = new ByteArrayOutputStream()) {
            ProtostuffIOUtil.writeListTo(bos, list, schema, LinkedBuffer.allocate(1024 * 1024));
            return bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("리스트 직렬화 중 오류 발생.", e);
        }
    }

    public static <T> List<T> deserializeList(byte[] data, Class<T> clazz) {
        if (data == null || data.length == 0) throw new RuntimeException("데이터가 비어 있습니다.");
        var schema = RuntimeSchema.getSchema(clazz);
        return ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(data), schema);
    }
}

Redis 유틸리티 클래스

다음은 Redis의 다양한 데이터 구조를 다루는 유틸리티 클래스입니다.

import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class RedisHelper {
    private final StringRedisTemplate redisTemplate;

    public RedisHelper(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // Key 관련 메서드
    public void removeKey(String key) {
        redisTemplate.delete(key);
    }

    public boolean existsKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public void setExpiry(String key, long seconds) {
        redisTemplate.expire(key, Duration.ofSeconds(seconds));
    }

    // String 관련 메서드
    public void setValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

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

    public Long increment(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    // Hash 관련 메서드
    public Object getHashValue(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }

    public void setHashValue(String key, Map<String, String> fields) {
        redisTemplate.opsForHash().putAll(key, fields);
    }

    // List 관련 메서드
    public Long pushToList(String key, String value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    public String popFromList(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    // Set 관련 메서드
    public Long addToSet(String key, String... values) {
        return redisTemplate.opsForSet().add(key, values);
    }

    public Set<String> membersOfSet(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    // ZSet 관련 메서드
    public Boolean addToZSet(String key, String member, double score) {
        return redisTemplate.opsForZSet().add(key, member, score);
    }

    public Set<String> rangeFromZSet(String key, long start, long end) {
        return redisTemplate.opsForZSet().range(key, start, end);
    }
}

사용 방법

위의 클래스들은 Redis의 주요 데이터 구조(String, Hash, List, Set, ZSet)를 다루기 위한 다양한 메서드를 제공합니다. 예를 들어:

  • setValuegetValue는 단순 문자열 값을 저장하고 불러옵니다.
  • pushToListpopFromList는 리스트에 값을 추가하거나 제거합니다.
  • addToSetmembersOfSet는 집합 데이터를 관리합니다.

Spring Boot 환경에서 사용하려면 다음 의존성을 pom.xml에 추가하세요.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

그리고 Redis 설정을 application.properties 또는 application.yml에 추가합니다.

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

이제 @Autowired를 통해 RedisHelper를 주입하여 사용할 수 있습니다.

@Service
public class ExampleService {
    private final RedisHelper redisHelper;

    public ExampleService(RedisHelper redisHelper) {
        this.redisHelper = redisHelper;
    }

    public void saveData(String key, String value) {
        redisHelper.setValue(key, value);
    }

    public String getData(String key) {
        return redisHelper.getValue(key);
    }
}

태그: Redis StringRedisTemplate Protostuff SpringBoot

7월 16일 22:43에 게시됨