Redis JSON 读取总结(方法 2 - sendCommand()
)
💡 背景
在 Redis 中,我们存储了 JSON 数据,并希望通过 Jedis sendCommand()
方式读取 JSON 里的 "content"
字段。由于 jedis.jsonGet()
可能在旧版本不支持,我们使用手动发送 JSON.GET
命令的方法。
🔹 1. Redis JSON 结构
Redis 存储的数据格式如下:
{ "embedding": [...], "content": "这是存储在 Redis 里的文本内容" }
存储的 Redis Key 形如:
default:<UUID>
default:d2c506f3-0f69-4aeb-ae9b-9fd245438672
🔹 2. 使用 sendCommand()
读取 JSON
✅ Java 代码
import java.nio.charset.StandardCharsets; import redis.clients.jedis.Jedis; import redis.clients.jedis.commands.ProtocolCommand; public class RedisJsonFetcher { public static void main(String[] args) { try (Jedis jedis = new Jedis("localhost", 6379)) { // **拼接 Redis Key,确保格式正确** String redisKey = "default:d2c506f3-0f69-4aeb-ae9b-9fd245438672"; // **执行 JSON.GET 命令** Object jsonData = jedis.sendCommand(new ProtocolCommand() { @Override public byte[] getRaw() { return "JSON.GET".getBytes(); } }, redisKey, "$.content"); // **转换 byte[] 为 String** if (jsonData instanceof byte[]) { String content = new String((byte[]) jsonData, StandardCharsets.UTF_8); System.out.println("Redis Content: " + content); } else { System.out.println("Unexpected data type: " + jsonData); } } catch (Exception e) { e.printStackTrace(); } } }
🔹 3. 关键点
✅ 确保 Key 拼接 default:
前缀(避免找不到数据)
✅ 使用 sendCommand()
发送 JSON.GET
命令
✅ Redis 返回 byte[]
,需要转换为 String
:
new String((byte[]) jsonData, StandardCharsets.UTF_8)
🔹 4. 可能遇到的问题
问题 | 原因 | 解决方案 |
---|---|---|
null 返回 | Key 可能不存在 | 使用 KEYS default:* 检查 Key |
ERR unknown command 'JSON.GET' | Redis 未启用 JSON 模块 | 运行 MODULE LIST 检查是否安装 rejson |
java.lang.ClassCastException: [B cannot be cast to String | Redis 返回 byte[] ,但被错误转换 | 用 new String((byte[]) jsonData, StandardCharsets.UTF_8) 进行转换 |
1 在 8001 界面搜索default+id搜索成功 在java必须拼凑"default"+id
3
🔹 5. Redis CLI 调试
✅ 1. 检查 Key 是否存在
KEYS default:*
✅ 2. 直接在 Redis CLI 测试 JSON.GET
JSON.GET default:d2c506f3-0f69-4aeb-ae9b-9fd245438672 $.content
如果 null
,说明 Key 不存在或 JSON 结构错误。
✅ 3. 检查 Redis 是否启用了 JSON 模块
MODULE LIST
如果没有 rejson
,需要安装:
redis-server --loadmodule /path/to/rejson.so
或者 Docker:
docker run -d --name redis-json -p 6379:6379 redislabs/rejson:latest
🔹 6. 总结
步骤 | 要点 |
---|---|
拼接 Key | String redisKey = "default:" + vectorId; |
发送 JSON.GET 命令 | jedis.sendCommand(new ProtocolCommand() {...}, redisKey, "$.content"); |
转换 byte[] | new String((byte[]) jsonData, StandardCharsets.UTF_8); |
检查 Key 是否存在 | KEYS default:* |
检查 Redis JSON 模块 | MODULE LIST |
🎉 至此,你已经成功使用 sendCommand()
方式查询 Redis JSON 数据!🚀