[REDIS] 📚 캐시(Cache) 설계 전략 지침 💯 총정리

1. Redis에 자동완성 관련 데이터를 Z-Set에 집어넣는다

2. ZSetOperation을 통해 Z-Set 관련 데이터를 가져온다.

3. 들어온 word로 시작하는 단어 중 완성된 단어를 뽑는다.

package com.finp.moic.autoComplete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

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

@Service
public class AutoCompleteService {

    RedisTemplate<String, String> redisTemplate;
    private final String key;
    @Autowired
    public AutoCompleteService(@Qualifier("redisTemplate1") RedisTemplate<String, String> redisTemplate,
                               @Value("${autocomplete-key}")String key) {
        this.redisTemplate = redisTemplate;
        this.key = key;
    }

    public List<String> getAutoComplete(String word) {

        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        List<String> autoCompleteList = new ArrayList<String>();

        Long rank = zSetOperations.rank(key,word);
        System.out.println(rank);

        if (rank != null) {
            Set<String> rangeList = zSetOperations.range(key,rank,rank + 1000);
            autoCompleteList = rangeList.stream().filter(value -> value.endsWith("*") && value.startsWith(word))
                    .map(value -> value.substring(0,value.length() - 1))
                    .toList();
        }
        return autoCompleteList;
    }
}