package org.ts.ddcs.tool;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;


/**
 * @author dylan
 */
public class RedisHelper {
    public static String queryValueBySimKey(String key, RedisTemplate redisTemplate) {
        if (null != key && null != redisTemplate) {
            Set<String> keys = redisTemplate.keys(key);
            if (null != keys && keys.size() == 1) {
                String keyJson = keys.iterator().next();
                if (null != keyJson && keyJson.length() > 0) {
                    ValueOperations<String, String> ops = redisTemplate.opsForValue();
                    if (null != ops) {
                        String value = ops.get(keyJson);
                        if (null != value) {
                            return value;
                        }
                    }
                }
            }
        }
        return null;
    }

    public static boolean hasKey(String key, RedisTemplate redisTemplate) {
        if (null != key && null != redisTemplate) {
            return redisTemplate.hasKey(key);
        }
        return false;
    }


    public static List<String> queryValueListBySimKey(String key, RedisTemplate redisTemplate) {
        List<String> valueList = new LinkedList<>();
        if (null != key && null != redisTemplate) {
            Set<String> keys = redisTemplate.keys(key);
            if (null != keys) {
                ValueOperations<String, String> ops = redisTemplate.opsForValue();
                for (String kv : keys) {
                    if (null != ops) {
                        String value = ops.get(kv);
                        if (null != value) {
                            valueList.add(value);
                        }
                    }
                }
            }
        }
        return valueList;
    }

}
