package com.xueyi.common.redis.utils;

import com.alibaba.fastjson2.JSONObject;
import com.xueyi.common.core.utils.core.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yk
 * @description
 * @date 2023-09-21 13:57
 */
public class RedisUtil {

    private static RedisTemplate<String, Serializable> redisTemplate;

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate2;

    @PostConstruct
    public void init() {
        redisTemplate = redisTemplate2;
    }

    public static Integer getNumberVal(String key) {
        return NumberUtil.getNumber((Integer) redisTemplate.opsForValue().get(key));
    }

    public static void expire(String key, int seconds) {
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }

    public static List<JSONObject> getJsonList(String key) {
        return redisTemplate.opsForList().range(key, 0, -1).stream().map(json-> JSONObject.parseObject(json.toString())).collect(Collectors.toList());
    }

    public static Boolean existed(String key){
        return  redisTemplate.hasKey(key);
    }
}
