Spring에서 Redis와 상호작용할 수 있도록 제공하는 클래스

사용 예시

생성자 주입받아 사용, 제너릭 타입은 키, 밸류 타입 지정

@Service
@RequiredArgsConstructor // Lombok 생성자 주입 어노테이션, 필드에 final 필수
public class MemberService{

	private final RedisTemplate<String, String> redisTemplate;
	
	// 비즈니스 로직 구현
}

데이터 저장

public <T> void put(RedisKey key, T value, int durationOfSec){
    try{
        String json = jsonSerializer.serialize(value);

        redisTemplate.opsForValue().set(
                key.toString(),                    // 키
                json,                              // 밸류
                Duration.ofSeconds(durationOfSec)  // 만료 시간(TTL)
        );
    } catch (Exception e) {
        throw new BusinessLogicException(ExceptionType.REDIS_CONNECTION_LOST);
    }
}

조회

public <T> Optional<T> get(RedisKey key, Class<T> clazz){
    try{
        String json = redisTemplate.opsForValue().get(key.toString());
        if(json == null) return Optional.empty();

        T value = jsonSerializer.deserialize(json, clazz);
        return Optional.ofNullable(value);
    } catch (Exception e) {
        throw new BusinessLogicException(ExceptionType.REDIS_CONNECTION_LOST);
    }
}

갱신

public <T> void update(RedisKey key, T updatedValue, BusinessLogicException e){
    long ttl = getTtlOfSecOrThrow(key, e);

    if(ttl >= Integer.MAX_VALUE){ // 키는 있지만 만료 없음
        put(key, updatedValue);
    }else{
        put(key, updatedValue, (int) ttl);
    }
}

삭제

public void remove(RedisKey key){
    try{
        redisTemplate.delete(key.toString());
    } catch (Exception e) {
        throw new BusinessLogicException(ExceptionType.REDIS_CONNECTION_LOST);
    }
}