spring-boot - 使用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 中的字符串。
解决方案
获取密钥类型的 Redis 命令是TYPE
:https ://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 在生产中通常更好,因为它不会尝试一次获取和返回所有密钥。
推荐阅读
- java - 迁移到 Jetty 9.4.25 的多个 SSL 设置问题
- javascript - React Native 读取 JSON 对象
- jmeter - JMeter 分发负载测试错误:连接拒绝主机
- android - android中的无限动画不起作用
- javascript - 汽车游戏中的箭头键
- python - 当 import math 被写入两次时,是否在第二个 import math 语句期间创建了引用?
- jquery - 当授权标志为否时,使指定单元格在 Ken do Grid 中只读
- reactjs - 从两个不同的静态构建目录提供 React 构建文件
- asp.net-web-api - 使用 Asp.net Web Api 和 Angular 8 下载文件
- android-fragments - 从 Kotlin 片段中的 Activity 获取上下文