package com.fzm.mall.server.admin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wangpeng
 * @version 1.0
 * @description
 * @create_time 2020/7/28 0028 17:31:15
 */
@Component
public class Redis {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisMapTemplate;

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

    public void setKey(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void setKey(String key, String value, long activeTime) {
        redisTemplate.opsForValue().set(key, value, activeTime, TimeUnit.SECONDS);
    }

    public void expire(String key, long activeTime) {
        redisTemplate.expire(key, activeTime, TimeUnit.SECONDS);
    }

    public Long incr(String key) {
        return redisTemplate.opsForValue().increment(key, 1);
    }

    public void del(String key) {
        redisTemplate.delete(key);
    }

    public void setHashKey(String key, String field, String value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    public String getHashKey(String key, String field) {
        return (String) redisTemplate.opsForHash().get(key, field);
    }

    public List<Object> getHashKeys(String key) {
        return redisTemplate.opsForHash().values(key);
    }

    public void push(String key, String val) {
        redisTemplate.opsForList().leftPush(key, val);
    }

    public String pop(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }

    public List<String> lRange(String k, long l, long l1) {
        return redisTemplate.opsForList().range(k, l, l1);
    }

    public Boolean setNx(String k) {
        if (redisTemplate.opsForValue().setIfAbsent(k, new Date().getTime() + "")) {
            redisTemplate.expire(k, 5, TimeUnit.SECONDS);
            return true;
        }
        return false;
    }

    public void deleteByMapKey(String key){
        redisMapTemplate.delete(key);
    }
}
