RedisUtil工具类

张军 642 0

ServiceException.java

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package zj.common.exception;

public class ServiceException extends RuntimeException {
    public ServiceException() {
    }

    public ServiceException(String var1) {
        super(var1);
    }

    public ServiceException(String var1, Throwable var2) {
        super(var1, var2);
    }

    public ServiceException(Throwable var1) {
        super(var1);
    }
}

BeansUtil.java

package project.framework.util;

import org.springframework.context.ApplicationContext;

/**
 * @author SHNKCS 张军 {@link  <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a>&nbsp;&nbsp;&nbsp;&nbsp;<a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>}
 * @version 1.00 2020/8/1
 */
public class BeansUtil {
    private static ApplicationContext appliactionContext;

    public static void setAppliactionContext(ApplicationContext ac) {
        appliactionContext = ac;
    }

    public static ApplicationContext getAppliactionContext() {
        return appliactionContext;
    }

    public static Object getBean(String name) {
        return appliactionContext.getBean(name);
    }
}

RedisUtil.java

package project.framework.util;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import zj.common.exception.ServiceException;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author SHNKCS 张军 {@link  <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a>&nbsp;&nbsp;&nbsp;&nbsp;<a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>}
 * 在Redis中数据都是以key-value的形式存储的,key规定只能是string类型的,所以我们所讨论的数据量类型默认是对value来说的
 */
public final class RedisUtil {

    private static RedisTemplate redisTemplate;

    static {
        redisTemplate = (RedisTemplate) BeansUtil.getBean("redisTemplate");
    }
    // =============================common============================

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间
     * @param unit 时间格式
     * @return
     */
    public static Boolean expire(String key, long time, TimeUnit unit) {
        try {
            if (time > 0) {
                return redisTemplate.expire(key, time, unit);
            }
            return false;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public static Boolean expire(String key, long time) {
        return expire(key, time, TimeUnit.SECONDS);
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key  键 不能为null
     * @param unit 时间格式
     * @return 时间(秒) 返回0代表为永久有效
     */
    public static Long getExpire(String key, TimeUnit unit) {
        return redisTemplate.getExpire(key, unit);
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public static Long getExpire(String key) {
        return getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public static Boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public static <K> void delete(K key) {
        redisTemplate.delete(key);
    }

    // ============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public static <String, V> V get(String key) {
        try {
            return ((ValueOperations<String, V>) redisTemplate.opsForValue()).get(key);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     */
    public static <String, V> void set(String key, V value) {
        try {
            ((ValueOperations<String, V>) redisTemplate.opsForValue()).set(key, value);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间 time要大于0 如果time小于等于0 将设置无限期
     * @param unit  时间格式
     * @return true成功 false 失败
     */
    public static <String, V> void set(String key, V value, long time, TimeUnit var5) {
        try {
            if (time > 0) {
                ((ValueOperations<String, V>) redisTemplate.opsForValue()).set(key, value, time, var5);
            } else {
                set(key, value);
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public static <String, V> void set(String key, V value, long time) {
        set(key, value, time, TimeUnit.SECONDS);
    }

    /**
     * 递增/递减
     *
     * @param key   键
     * @param delta 递增值(大于0递增因子,小于0递减因子)
     * @return
     */
    public static <String, V> Long increment(String key, long delta) {
        return ((ValueOperations<String, V>) redisTemplate.opsForValue()).increment(key, delta);
    }

    // ================================Map=================================

    /**
     * Map设置值
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public static <String, HK, HV> void putAll(String key, Map<? extends HK, ? extends HV> map) {
        try {
            ((HashOperations<String, HK, HV>) redisTemplate.opsForHash()).putAll(key, map);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 获取map中的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public static <String, HK, HV> HV get(String key, HK item) {
        return ((HashOperations<String, HK, HV>) redisTemplate.opsForHash()).get(key, item);
    }

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

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     */
    public static <String, HK, HV> void put(String key, HK item, HV value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public static <String, HK> Long delete(String key, HK... item) {
        return redisTemplate.opsForHash().delete(key, item);
    }

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

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

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */
    public static double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

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

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    public static 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 static 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 static long sSet(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 static long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

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

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public static long setRemove(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 start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return
     */
    public static List<Object> lGet(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 static long lGetListSize(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 static Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public static boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public static boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public static boolean lSet(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 static boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */
    public static boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public static long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}

测试工具类

@Test
public void 测试缓存() {
    RedisUtil.set("sks", "字符串值1");
    RedisUtil.set("ski", 1);
    RedisUtil.set("skd", new Date());
    Map<String, Object> m = new HashMap<>();
    m.put("ska", "va");
    m.put("skb", 2);
    RedisUtil.set("skm1", m);
    m.put("skc", new Date());
    //一定先设置值再缓存
    RedisUtil.set("skm1", m);
    RedisUtil.set("skm2", m);
    String vs = RedisUtil.get("sks");
    Integer vi = RedisUtil.get("ski");
    Date vd = RedisUtil.get("skd");
    Map<String, Object> vm = RedisUtil.get("skm");


    System.out.println("值字符串:" + vs);
    System.out.println("值数字:" + vi);
    System.out.println("值日期:" + vd);
    System.out.println("值map:" + vm);

    m = new HashMap<>();
    m.put("hka", "va");
    m.put("hkb", 2);
    m.put("hkc", new Date());
    m.put("hm2", "m2v");
    RedisUtil.putAll("hkm2", m);
    Map<String, Object> vm2 = RedisUtil.entries("hkm2");
    System.out.println("值map:" + vm2);
    RedisUtil.put("hkm2", "ha", "hv");
    vm2 = RedisUtil.entries("hkm2");
    System.out.println("值map:" + vm2);

}



更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论