redis工具类封装,redis的使用方式新增修改删除等,

public class RedisUtil {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private  HashOperations<String, String, Object> hashOperations;

    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.hashOperations = redisTemplate.opsForHash();
    }
    /**
     * 根据key 设置有效时间, 到期后该key 对应的数据将会清除
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean setExpireByKey(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }

    }

    /**
     * 根据key 获取该数据的有效剩余时间(秒)
     * 返回 -1  表示没有设置有效时间
     *
     * @param key 键不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpireByKey(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);

    }


    /**
     * 通过key 判断数据是否存在
     * @return true 存在 false不存在
     */

    public boolean isExistByKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 根据key 删除redis 的数据
     * @param key 可以传一个值 或多个
     */
    public long deleteDataByKeys(String... key) {
        long delNum = 0;
        try {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    if (redisTemplate.delete(key[0])) {
                        delNum = 1;
                    }
                } else {
                    delNum = redisTemplate.delete((Collection)CollectionUtils.arrayToList(key));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return delNum;
        }
        return delNum;
    }


    /**
     * 根据key 获取数据
     *
     * @param key 键
     * @return 值
     */
    public Object getDataByKey(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);

    }


    /**
     * 将数据存放到redis 中
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean setDataToRedis(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 存入数据到redis 并设置有效时间(秒)
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean setDataAndSetExpireTime(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                setDataToRedis(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 根据key 增加到对应的value 数值
     * 数据递增使用
     *
     * @param key 键
     * @param num 要增加几(大于0)
     * @return
     */
    public long incrementDataByKey(String key, long num) {
        if (num < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, num);

    }


    /**
     * 根据key 递减到对应的value 数值
     *
     * @param key 键
     * @param num 要减少几(小于0)
     * @return
     */
    public long decrDataByKey(String key, long num) {
        if (num < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -num);
    }


    /**
     * 获取hash表数据中的key value 数据
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object getMapByHashKey(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }


    /**
     * 获取hash表所以数据
     * * @param key 键
     *
     * @return 对应的多个键值
     */
    public Map<Object, Object> getHashDataByKey(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    public Map<Object, Object> getHashDataByKeyMap(String key) {
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        return hashOperations.entries(key);
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键 为hash名
     * @param item  项 map 的key
     * @param value 值 map 的value
     * @return true 成功 false失败
     */
    public boolean putHashData(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 向一张hash表中放入批量map数据,如果不存在将创建
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean putAllHashData(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }

    }
    public boolean deleteHashData(String key, String field) {
        try {
            // 检查特定字段是否已经存在
            boolean fieldExists = hashOperations.hasKey(key, field);

            if (fieldExists) {
                // 如果字段存在,则删除特定键值对
                hashOperations.delete(key, field);
                return true;
            } else {
                // 如果字段不存在,可以选择抛出异常或进行其他处理
                // 这里假设您希望在字段不存在时什么也不做
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean deleteHashData(String key, String field, Object value) {
        try {
            // 获取特定字段的值
            Object storedValue = hashOperations.get(key, field);

            if (storedValue != null && storedValue.equals(value)) {
                // 如果字段存在并且值匹配,则删除特定键值对
                hashOperations.delete(key, field);
                return true;
            } else {
                // 如果字段不存在或值不匹配,可以选择抛出异常或进行其他处理
                // 这里假设您希望在字段不存在或值不匹配时什么也不做
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    public boolean modifyHashFieldValue(String key, String field, Object newValue) {
        try {
            // 检查特定字段是否已经存在
            boolean fieldExists = hashOperations.hasKey(key, field);

            if (!fieldExists) {
                // 如果字段不存在,则将新字段和值添加到哈希表中
                hashOperations.put(key, field, newValue);
                return true;
            } else {
                // 如果字段已经存在,可以选择抛出异常或进行其他处理
                // 这里假设您希望在字段已经存在时什么也不做
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean modifyHashValue(String key, String field, Object newValue) {
        try {
            // 获取特定字段的值
            Object oldValue = hashOperations.get(key, field);

            if (oldValue != null) {
                // 修改特定字段的值
                hashOperations.put(key, field, newValue);
                return true;
            } else {
                // 如果字段不存在,则抛出异常或进行其他处理
                // 这里假设您希望在字段不存在时什么也不做
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入单个map数据,并设置Hash表的有效时间,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean putHashDataSetExpireTime(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                setExpireByKey(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 向一张hash表中放入批量map数据,并且设置有效时间如果不存在将创建
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean putAllHashDataSetExpireTime(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                setExpireByKey(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }

    }


    /**
     * 根据hashkey+mapkey 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void deleteHashDataByKeys(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    public void fuzzyDelete(String prefix) {
        prefix = prefix + "**";
        // 根据模糊的 key 查询匹配的 key 集合
        Set<String> keys = redisTemplate.keys(prefix);
        // 遍历匹配的 key 集合,进行删除操作
        for (String key : keys) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean isHaveDataByKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }


    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param HashKey 键
     * @param mapKey  项
     * @param num     要增加几(大于0)
     * @return
     */
    public double increNumByHashKey(String HashKey, String mapKey, double num) {
        return redisTemplate.opsForHash().increment(HashKey, mapKey, num);
    }


    /**
     * hash递减 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param HashKey 键
     * @param mapKey  项
     * @param num     要减少记(小于0)
     * @return
     */
    public double decreNumByHashKey(String HashKey, String mapKey, double num) {
        return redisTemplate.opsForHash().increment(HashKey, mapKey, -num);
    }


    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }

    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }

    }


    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long addDataToSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;

        }

    }


    /**
     * 将数据放入set缓存并且设置有效时间
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long addDataToSetAndSetTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                setExpireByKey(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }


    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public long getSetSizeByKey(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 删除Set集合中的值
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long removeDataFromSet(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // ===============================list=================================


    /**
     * 将数据放入list缓存中
     *
     * @param key   键
     * @param value 值
     * @param
     * @return
     */
    public boolean addDataToList(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将list集合数据放入List缓存
     *
     * @param key   键
     * @param value 值
     * @param
     * @return
     */
    public boolean addListDataToList(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 将数据放入list缓存,并设置有效时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean addDataToListAndSetTime(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                setExpireByKey(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将List数据放入list缓存,并设置有效时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean addListDataToListAndSetTime(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                setExpireByKey(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据下标范围获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return
     */
    public List<Object> getDataFromListByRange(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */
    public long getListSizeByKey(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object getDataByKeyAndIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */

    public boolean updateListDataByKeyAndIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 在List删除多个指定的值
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long removeListDataByKeyAndValue(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public  Boolean  setIfAbsent(String key, String  value, long timeout, TimeUnit unit){
        Boolean isLocked = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, unit);
        return isLocked;
    }

    public long getKeyExpiration(String key) {
        // 获取键的剩余生存时间,以秒为单位
        return redisTemplate.opsForValue().getOperations().getExpire(key, TimeUnit.SECONDS);
    }

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq1814022510

谢谢你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值