JAVA中redis的各种方法的封装---通用方法

本文介绍了如何使用Redis进行各种操作,包括根据key判断类型、删除、移动、模糊查询、随机生成key、切换数据库索引、批量删除、检查键存在、设置过期时间和获取/删除过期时间等。
摘要由CSDN通过智能技术生成

根据key判断值的类型

    /**
     * 根据key判断值 类型
     *
     * @param key 键
     * @return DataType
     */
    public DataType typeOfKey(String key) {
        return key == null ? null : redisTemplate.type(key);
    }

根据key删除

    /**
     * 删除 key
     *
     * @param key 键
     * @return Boolean 删除是否成功
     */
    public Boolean delete(String key) {
        return key != null && Boolean.TRUE.equals(redisTemplate.delete(key));
    }

将当前数据库的key移动到指定dbIndex中

    /**
     * 将当前数据库的key 移动到指定dbIndex的库中
     *
     * @param key     键
     * @param dbIndex 数据库index
     * @return 移动结果
     */
    public boolean move(String key, int dbIndex) {
        try {
            return redisTemplate.move(key, dbIndex);
        } catch (NullPointerException e) {
            log.error("空指针异常");
            return false;
        }
    }

模糊查询

    /**
     * 根据pattern 模糊查询所有key
     *
     * @param pattern 模糊查询字符串
     * @return 查询到的key集合
     */
    public Set<String> scan(String pattern) {
        //需要匹配的key
        ScanOptions options = ScanOptions.scanOptions()
                //这里指定每次扫描key的数量,建议1000-10000之间(很多博客瞎说要指定Integer.MAX_VALUE
                .count(3000)
                .match(pattern).build();
        RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
        Cursor<String> cursor = redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize));
        Set<String> result = new HashSet<>();
        while (cursor.hasNext()) {
            result.add(cursor.next());
        }
        //切记这里一定要关闭,否则会耗尽连接数。报Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a
        cursor.close();
        return result;
    }

随机生成key

    /**
     * 随机生成key
     *
     * @return 随机生成key
     */
    public String randomKey() {
        return redisTemplate.randomKey();
    }

实现db索引切换

    /**
     * selectDb命令 实现db索引切换
     *
     * @param databaseIndex 要切换的索引
     */
    public void selectDb(int databaseIndex) {
        redisTemplate.getConnectionFactory().getConnection().select(databaseIndex);
    }

删除多个key

    /**
     * 删除keys
     *
     * @param key 可以传一个值 或多个
     */
    public int del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                boolean isDel = redisTemplate.delete(key[0]);
                return isDel ? 1 : 0;
            } else {
                return Math.toIntExact(redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key))
                );
            }
        } else {
            return 0;
        }
    }

判断是否存在key

    /**
     * 判断是是否存在key
     *
     * @param key 要判断的key
     * @return 判断结果
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

指定缓存失效时间

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return boolean
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

根据key获取过期时间

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

删除key的过期时间

    /**
     * 删除key的过期时间
     *
     * @param key 键 不能为null
     * @return boolean 删除是否成功
     */
    public Boolean persist(String key) {
        return redisTemplate.persist(key);
    }
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值