redis工具类

一、代码

package com.hl.scriptDemo.util;

import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * Redis工具类
 */
@Component
@SuppressWarnings({"unchecked", "rawtypes"})
public class RedisUtils {
    private static final Logger logger = Logger.getLogger(RedisUtils.class.getSimpleName());
    private final RedisTemplate redisTemplate;

    public RedisUtils(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;

    }

    /**
     * 根据key 获取过期时间
     *
     * @param key      键 不能为null
     * @param timeUnit 时间单位
     * @return 时间(秒) 返回 0 代表为永久有效,-2 代表键不存在
     */
    public <K> long getExpireTime(K key, TimeUnit timeUnit) {
        Long expire = redisTemplate.getExpire(key, timeUnit == null ? TimeUnit.SECONDS : timeUnit);
        if (expire != null) {
            return expire;
        }
        return -2;
    }

    /**
     * 指定缓存失效时间
     *
     * @param key        键
     * @param expireTime 时间(秒)
     * @param timeUnit   时间单位
     */
    public <K> void setExpireTime(K key, long expireTime, TimeUnit timeUnit) {
        try {
            if (expireTime > 0) {
                redisTemplate.expire(key, expireTime, timeUnit == null ? TimeUnit.SECONDS : timeUnit);
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * 移除指定 key 的过期时间
     *
     * @param key 键
     */
    public <K> void removeExpireTime(K key) {
        redisTemplate.boundValueOps(key).persist();
    }

    /**
     * 获取缓存中所有的键
     *
     * @param key 键
     * @return 缓存中所有的键
     */
    public <K> Set<K> keys(K key) {
        return redisTemplate.keys(key);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public <K> boolean hasKey(K key) {
        try {
            return Boolean.TRUE.equals(redisTemplate.hasKey(key));
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
            return false;
        }
    }

    /**
     * 根据key删除缓
     *
     * @param keys 键
     */
    public <K> void delete(Collection<K> keys) {
        redisTemplate.delete(keys);
    }


    /**
     * 设置分布式锁
     *
     * @param key    键,可以用用户主键
     * @param value  值,可以传requestId,可以保证锁不会被其他请求释放,增加可靠性
     * @param expire 锁的时间
     * @return 设置成功为 true
     */
    public <K, V> Boolean setNx(K key, V value, long expire) {
        return this.setNx(key, value, expire, TimeUnit.SECONDS);
    }

    /**
     * 设置分布式锁
     *
     * @param key      键,可以用用户主键
     * @param value    值,可以传requestId,可以保证锁不会被其他请求释放,增加可靠性
     * @param expire   锁的时间
     * @param timeUnit 时间单位
     * @return 设置成功为 true
     */
    public <K, V> Boolean setNx(K key, V value, long expire, TimeUnit timeUnit) {
        return redisTemplate.opsForValue().setIfAbsent(key, value, expire, timeUnit);
    }


    /**
     * 设置分布式锁,有等待时间
     *
     * @param key     键,可以用用户主键
     * @param value   值,可以传requestId,可以保证锁不会被其他请求释放,增加可靠性
     * @param expire  锁的时间(秒)
     * @param timeout 在timeout时间内仍未获取到锁,则获取失败
     * @return 设置成功为 true
     */
    public <K, V> Boolean setNx(K key, V value, long expire, long timeout) {
        return this.setNx(key, value, expire, timeout, TimeUnit.SECONDS);
    }


    /**
     * 设置分布式锁,有等待时间
     *
     * @param key      键,可以用用户主键
     * @param value    值,可以传requestId,可以保证锁不会被其他请求释放,增加可靠性
     * @param expire   锁的时间
     * @param timeout  在timeout时间内仍未获取到锁,则获取失败
     * @param timeUnit 时间单位
     * @return 设置成功为 true
     */
    public <K, V> Boolean setNx(K key, V value, long expire, long timeout, TimeUnit timeUnit) {
        long start = System.currentTimeMillis();
        //在一定时间内获取锁,超时则返回错误
        for (; ; ) {
            // 获取到锁,并设置过期时间返回true
            if (Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, value, expire, timeUnit))) {
                return true;
            }
            //否则循环等待,在timeout时间内仍未获取到锁,则获取失败
            if (System.currentTimeMillis() - start > timeout) {
                return false;
            }
        }
    }

    /**
     * 释放分布式锁
     *
     * @param key   锁
     * @param value 值,可以传requestId,可以保证锁不会被其他请求释放,增加可靠性
     * @return 成功返回true, 失败返回false
     */
    public <K, V> boolean releaseNx(K key, V value) {
        Object currentValue = redisTemplate.opsForValue().get(key);
        if (String.valueOf(currentValue) != null && value.equals(currentValue)) {
            return Boolean.TRUE.equals(redisTemplate.opsForValue().getOperations().delete(key));
        }
        return false;
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     */
    public <K, V> void set(K key, V value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key      键
     * @param value    值
     * @param time     时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @param timeUnit 时间单位
     */
    public <K, V> void set(K key, V value, long time, TimeUnit timeUnit) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, timeUnit == null ? TimeUnit.SECONDS : timeUnit);
            } else {
                redisTemplate.opsForValue().set(key, value);
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * value增加值
     *
     * @param key    键
     * @param number 增加的值
     * @return 返回增加后的值
     */
    public Long incrBy(String key, long number) {
        return (Long) redisTemplate.execute((RedisCallback<Object>) connection -> connection.stringCommands().incrBy(key.getBytes(), number));
    }

    /**
     * value减少值
     *
     * @param key    键
     * @param number 减少的值
     * @return 返回减少后的值
     */
    public Long decrBy(String key, long number) {
        return (Long) redisTemplate.execute((RedisCallback<Object>) connection -> connection.stringCommands().decrBy(key.getBytes(), number));
    }

    /**
     * 根据key获取value
     *
     * @param key 键
     * @return 返回值
     */
    public <K, V> V get(K key) {
        BoundValueOperations<K, V> boundValueOperations = redisTemplate.boundValueOps(key);
        return boundValueOperations.get();
    }


    /**
     * 将value从右边放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public <K, V> void listRightPush(K key, V value) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        //从队列右插入
        listOperations.rightPush(key, value);
    }

    /**
     * 将value从左边放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public <K, V> void listLeftPush(K key, V value) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        //从队列右插入
        listOperations.leftPush(key, value);
    }

    /**
     * 将list从右边放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public <K, V> void listRightPushAll(K key, List<V> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * 将list从左边放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public <K, V> void listLeftPushAll(K key, List<V> value) {
        try {
            redisTemplate.opsForList().leftPushAll(key, value);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return 返回列表中的值
     */
    public <K, V> V listGetWithIndex(K key, long index) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        return listOperations.index(key, index);
    }

    /**
     * 从list左边弹出一条数据
     *
     * @param key 键
     * @return 队列中的值
     */
    public <K, V> V listLeftPop(K key) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        return listOperations.leftPop(key);
    }

    /**
     * 从list左边定时弹出一条
     *
     * @param key     键
     * @param timeout 弹出时间
     * @param unit    时间单位
     * @return 队列中的值
     */
    public <K, V> V listLeftPop(K key, long timeout, TimeUnit unit) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        return listOperations.leftPop(key, timeout, unit);
    }

    /**
     * 从list右边弹出一条数据
     *
     * @param key 键
     * @return 队列中的值
     */
    public <K, V> V listRightPop(K key) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        return listOperations.rightPop(key);
    }

    /**
     * 从list左边定时弹出
     *
     * @param key     键
     * @param timeout 弹出时间
     * @param unit    时间单位
     * @return 队列中的值
     */
    public <K, V> V listRightPop(K key, long timeout, TimeUnit unit) {
        ListOperations<K, V> listOperations = redisTemplate.opsForList();
        return listOperations.leftPop(key, timeout, unit);
    }

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始下标
     * @param end   结束下标  0 到 -1 代表所有值
     * @return list内容
     */
    public <K, V> List<V> listRange(K key, long start, long end) {
        try {
            ListOperations<K, V> listOperations = redisTemplate.opsForList();
            return listOperations.range(key, start, end);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return list长度
     */
    public <K> long listSize(K key) {
        Long size = redisTemplate.opsForList().size(key);
        return Objects.requireNonNullElse(size, 0).longValue();
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 下标
     * @param value 值
     */
    public <K, V> void listSet(K key, long index, V value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * 从list中移除N个值为value的值
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public <K, V> long listRemove(K key, long count, V value) {
        Long count1 = redisTemplate.opsForList().remove(key, count, value);
        if (count1 != null) {
            return count1;
        }
        return 0;
    }


    /**
     * 根据key和键获取value
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public <K, HK, HV> HV hashGet(K key, String item) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.get(key, item);
    }

    /**
     * 获取key对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public <K, HK, HV> Map<HK, HV> hashMGet(K key) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.entries(key);
    }

    /**
     * 添加map到hash中
     *
     * @param key 键
     * @param map 对应多个键值
     */
    public <K> void hashMSet(K key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * 添加map到hash中,并设置过期时间
     *
     * @param key        键
     * @param map        对应多个键值
     * @param expireTime 时间(秒)
     */
    public <K> void hashMSet(K key, Map<String, Object> map, long expireTime) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (expireTime > 0) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * 向hash表中放入一个数据
     *
     * @param key   键
     * @param hKey  map 的键
     * @param value 值
     */
    public <K, HK, HV> void hashPut(K key, HK hKey, HV value) {
        try {
            HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
            hashOperations.put(key, hKey, value);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * 向hash表中放入一个数据,并设置过期时间
     *
     * @param key        键
     * @param hKey       map 的键
     * @param value      值
     * @param expireTime 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     */
    public <K, HK, HV> void hashPut(K key, HK hKey, HV value, long expireTime) {
        try {
            redisTemplate.opsForHash().put(key, hKey, value);
            if (expireTime > 0) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param hKey map 的键 不能为null
     * @return true 存在 false不存在
     */
    public <K, HK, HV> boolean hashHasKey(K key, HK hKey) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.hasKey(key, hKey);
    }

    /**
     * 取出所有 value
     *
     * @param key 键
     * @return map 中所有值
     */
    public <K, HK, HV> List<HV> hashValues(K key) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.values(key);
    }

    /**
     * 取出所有 hKey
     *
     * @param key 键
     * @return map 所有的键
     */
    public <K, HK, HV> Set<HK> hashHKeys(K key) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.keys(key);
    }

    /**
     * 删除hash表中的键值,并返回删除个数
     *
     * @param key      键
     * @param hashKeys 要删除的值的键
     * @return 删除个数
     */
    public <K, HK, HV> Long hashDelete(K key, Object... hashKeys) {
        HashOperations<K, HK, HV> hashOperations = redisTemplate.opsForHash();
        return hashOperations.delete(key, hashKeys);
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     */
    public <K, V> void setAdd(K key, V... values) {
        redisTemplate.opsForSet().add(key, values);
    }

    /**
     * 将set数据放入缓存,并设置过期时间
     *
     * @param key        键
     * @param expireTime 时间(秒)
     * @param values     值 可以是多个
     */
    public <K, V> void setAdd(K key, long expireTime, V... values) {
        redisTemplate.opsForSet().add(key, values);
        if (expireTime > 0) {
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return set缓存的长度
     */
    public <K> long setSize(K key) {
        Long size = redisTemplate.opsForSet().size(key);
        if (size != null) {
            return size;
        }
        return 0;
    }

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return Set中的所有值
     */
    public <K, V> Set<V> setValues(K key) {
        SetOperations<K, V> setOperations = redisTemplate.opsForSet();
        return setOperations.members(key);
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 要查询的值
     * @return true 存在 false不存在
     */
    public <K, V> boolean setHasKey(K key, V value) {
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, value));
    }

    /**
     * 根据value删除,并返回删除的个数
     *
     * @param key   键
     * @param value 要删除的值
     * @return 删除的个数
     */
    public <K, V> Long setDelete(K key, Object... value) {
        SetOperations<K, V> setOperations = redisTemplate.opsForSet();
        return setOperations.remove(key, value);
    }

    /**
     * 在 zSet中插入一条数据
     *
     * @param key   键
     * @param value 要插入的值
     * @param score 设置分数
     */
    public <K, V> void zSetAdd(K key, V value, long score) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        zSetOperations.add(key, value, score);
    }

    /**
     * 得到分数在 score1,score2 之间的值
     *
     * @param key    键
     * @param score1 起始分数
     * @param score2 终止分数
     * @return 范围内所有值
     */
    public <K, V> Set<V> zSetValuesRange(K key, long score1, long score2) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        return zSetOperations.range(key, score1, score2);
    }

    /**
     * 根据value删除,并返回删除个数
     *
     * @param key   键
     * @param value 要删除的值,可传入多个
     * @return 删除个数
     */
    public <K, V> Long zSetDeleteByValue(K key, Object... value) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        return zSetOperations.remove(key, value);
    }

    /**
     * 根据下标范围删除,并返回删除个数
     *
     * @param key       键
     * @param startSize 起始下标
     * @param endSize   结束下标
     * @return 删除个数
     */
    public <K, V> Long zSetDeleteRange(K key, long startSize, long endSize) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        return zSetOperations.removeRange(key, startSize, endSize);
    }

    /**
     * 删除分数区间内元素,并返回删除个数
     *
     * @param key        键
     * @param startScore 起始分数
     * @param endScore   终止分数
     * @return 删除个数
     */
    public <K, V> Long zSetDeleteByScore(K key, long startScore, long endScore) {
        ZSetOperations<K, V> zSetOperations = redisTemplate.opsForZSet();
        return zSetOperations.removeRangeByScore(key, startScore, endScore);
    }

}

二、 代码分析

RedisUtils

RedisUtils 是一个工具类,用于操作 Redis 数据库,主要提供了对 Redis 的各种操作接口,包括键值对的读写、过期时间设置、分布式锁的实现、列表、集合和有序集合的操作。

主要成员变量和构造方法
  1. logger: 日志记录器,用于记录异常信息。
  2. redisTemplate: RedisTemplate 实例,用于执行 Redis 操作。
方法概览
  • getExpireTime: 获取键的过期时间,返回秒数或 -2 表示键不存在。
  • setExpireTime: 设置键的过期时间。
  • removeExpireTime: 移除键的过期时间,使其变为永久有效。
  • keys: 获取所有匹配键的集合。
  • hasKey: 判断键是否存在。
  • delete: 删除一个或多个键。
  • setNx: 使用 setIfAbsent 方法实现原子性设置键值,如果键不存在则设置,存在则不设置。
  • releaseNx: 释放分布式锁,根据值判断是否拥有锁。
  • set: 设置键值对,没有过期时间。
  • setWithExpire: 设置键值对并设定过期时间。
  • incrBydecrBy: 分别用于增加和减少整数值。
  • get: 获取键对应的值。
  • listRightPushlistLeftPush: 分别将值添加到列表的右侧和左侧。
  • listRightPushAlllistLeftPushAll: 分别将列表添加到现有列表的右侧和左侧。
  • listGetWithIndex: 根据索引获取列表中的值。
  • listLeftPoplistRightPop: 分别从列表的左侧和右侧弹出一个元素。
  • listRange: 获取列表中指定范围的元素。
  • listSize: 获取列表的长度。
  • listSet: 修改列表中指定索引的值。
  • listRemove: 从列表中移除指定数量的匹配值。
  • hashGet: 从哈希表中获取指定键的值。
  • hashMGet: 获取哈希表中多个键的值。
  • hashMSethashMSetWithExpire: 分别设置哈希表中多对键值,可选设置过期时间。
  • hashPuthashPutWithExpire: 分别向哈希表中添加单个键值,可选设置过期时间。
  • hashHasKey: 判断哈希表中是否存在指定键。
  • hashValues: 获取哈希表中所有值。
  • hashHKeys: 获取哈希表中所有键。
  • hashDelete: 删除哈希表中的键值。
  • setAddsetAddWithExpire: 向集合中添加元素,可选设置过期时间。
  • setSize: 获取集合的大小。
  • setValues: 获取集合中的所有元素。
  • setHasKey: 判断集合中是否存在指定元素。
  • setDelete: 从集合中删除指定元素。
  • zSetAdd: 向有序集合中添加元素并设置分数。
  • zSetValuesRange: 获取有序集合中指定分数范围的元素。
  • zSetDeleteByValue: 根据值从有序集合中删除元素。
  • zSetDeleteRange: 根据下标范围从有序集合中删除元素。
  • zSetDeleteByScore: 根据分数范围从有序集合中删除元素。

注解与警告

  • @SuppressWarnings({"unchecked", "rawtypes"}): 这些注解用于抑制编译器的警告,关于类型转换和泛型的警告。

设计模式

  • 单例模式: RedisUtils 类通常设计为单例,但当前代码未实现单例,需要在使用时确保正确初始化和管理实例。
  • 工具类模式: 类提供静态方法,方便直接调用,无需实例化对象。

性能与最佳实践

  • 非线程安全: 类中的方法没有进行同步控制,如果在多线程环境下使用,需要额外的同步措施。
  • 异常处理: 多处使用了日志记录异常,但没有明确的异常处理策略,可能导致程序中断。
  • 过期时间处理: 使用 try-catch导致的代码中断,但异常处理 包裹,避免了异常可能过于简单,可能需要更详细的错误处理逻辑。
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值