개발 기록

> [Redis] Spring Data Redis 자료구조 - RedisTemplate 사용 방법 본문

SQL&NoSQL

> [Redis] Spring Data Redis 자료구조 - RedisTemplate 사용 방법

1z 2024. 2. 3. 20:54

 

1. class RedisTemplate<K,V> 

Redis 데이터 접근을 도와주는 helper class 이다.

K : redis key (usually a String)
V : redis value

- Lettuce는 기본적으로 직렬화 및 역직렬화를 관리하지만 직접 구성할 수 있다. 

- 스레드로부터 안전 하므로 멀티 스레드 환경 에서 잘 작동한다.
- redis 는 key , value 형태로 저장한다.

 

 

 

(1) Redis 데이터 타입 

 

 

 

(2) RedisTemplate date type method

메서드명 반환타입 Redis 자료구조 설명
opsForValue() ValueOperations String 문자열에 대한 작업
opsForStream StreamOperation Stream 스트림 값에 대한 작
opsForList() ListOperations List 리스트 값에 대한 작업
opsForSet() SetOperations Set  
opsForZSet() ZSetOperations Sorted Set  
opsForHash() HashOperations Hash hash 값에 대한 작업

 

 

 

 

2. 예제 

 

(1) String - opsForValue

// set
public void set(String key, String value, long ttl, TimeUnit unit){
    redisTemplate.opsForValue().set(key, value, ttl, unit);
}

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

 

 

(2) List - opsForList

// set
public void set(String key, List<String> values){
    redisTemplate.opsForList().rightPush(key, values);
}
// get
public List<String> get(String key){
    Long size = redisTemplate.opsForList().size(key);
    return len == 0 ? new ArrayList<>() : redisTemplate.opsForList().range(key, 0, size-1);
}

 

 

(3) Hash - opsForHash 

// ge
public void set(String key, HashMap<String, Object> value){
    redisTemplate.opsForHash().putAll(key, value);
}

// set
public Object get(String key, String hashKey){
    return redisTemplate.opsForHash().hasKey(key, hashKey) ? redisTemplate.opsForHash().get(key, hashKey) : new String();
}

 

 

(4) Set - opsForSet  & opsForZSet

// set 
public void set(String key, String... values){
    redisTemplate.opsForSet().add(key, values);
}

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

// sorted set
public void setSorted(String key, List<Struct.SortedSet> values){
    for(Struct.SortedSet v : values){
        redisTemplate.opsForZSet().add(key, v.getValue(), v.getScore());
    }
}

// sorted get
public Set getSorted(String key){
    Long len = redisTemplate.opsForZSet().size(key);
    return len == 0 ? new HashSet<String>() : redisTemplate.opsForZSet().range(key, 0, len-1);
}

 

 

 

 

 

 

 

참고

https://co-de.tistory.com/14

https://www.baeldung.com/spring-data-redis-properties