首页 > 解决方案 > 使用restTemplate检查redis键是哈希还是字符串

问题描述

我有由哈希和字符串组成的 Redis DB。

我使用以下代码从数据库中获取了所有密钥:

        Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());

        Iterator<byte[]> it = keys.iterator();

        while(it.hasNext()){

            byte[] data = (byte[])it.next();

            String key = (new String(data, 0, data.length));
            System.out.println(key);
        }

从这里:如何使用 redis 模板从 Redis 获取所有密钥

由于键可以是散列或字符串,如何确定何时可以使用 opsForHash 和 opsForValue 即如何使用restTemplate检查它是散列还是 Spring Boot 中的字符串。

标签: spring-bootredis

解决方案


获取密钥类型的 Redis 命令是TYPEhttps ://redis.io/commands/type

您可以使用 RedisTemplate 的public DataType type(K key)方法来执行此操作:https ://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/core/RedisTemplate.html#type-K-

这是一个例子:

Set<byte[]> keys = redisTemplate.getConnectionFactory().getConnection().keys("*".getBytes());

Iterator<byte[]> it = keys.iterator();

while(it.hasNext()){
    byte[] data = (byte[])it.next();
    String key = (new String(data, 0, data.length));

    DataType type = redisTemplate.type(key);

    if (type == DataType.HASH) {
       // ...
    } else if (type == DataType.STRING) {
       // ...
    }
}

编辑:还有一条建议是您可能想要使用SCAN而不是KEYS *(在您链接的 SO 问题的一个答案中提到)。Scan 在生产中通常更好,因为它不会尝试一次获取和返回所有密钥。


推荐阅读