Jedis 4.3.2版本中二进制键值对存储方案咨询(替代BinaryJedis)
在Jedis 4.3.2中存储二进制键值对的方案
Jedis 4.x 版本已经把原 BinaryJedis 的功能整合到核心的 Jedis 类以及官方推荐的 UnifiedJedis 类里了,不用再单独实例化 BinaryJedis 来处理二进制数据,直接用这两个类就能完成二进制键值对的存储与读取。
代码示例
1. 用 Jedis 类直接操作
import redis.clients.jedis.Jedis; public class BinaryDataDemo { public static void main(String[] args) { // 建立Redis连接(try-with-resources自动关闭连接) try (Jedis jedis = new Jedis("localhost", 6379)) { // 定义二进制键和值 byte[] binaryKey = "binary:user:avatar:1001".getBytes(); byte[] binaryValue = new byte[]{0x12, 0x34, 0x56, 0x78, 0x90}; // 存储二进制键值对 jedis.set(binaryKey, binaryValue); // 读取二进制值 byte[] fetchedValue = jedis.get(binaryKey); for (byte b : fetchedValue) { System.out.printf("%02X ", b); } // 示例:给二进制键设置过期时间(1小时) jedis.expire(binaryKey, 3600); } } }
2. 用 UnifiedJedis(Jedis 4.x 推荐方式)
import redis.clients.jedis.UnifiedJedis; public class UnifiedBinaryDemo { public static void main(String[] args) { try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) { byte[] hashKey = "binary:user:profile:1001".getBytes(); byte[] hashField = "avatar".getBytes(); byte[] hashValue = "用户头像二进制数据".getBytes(); // 哈希类型的二进制存储 jedis.hset(hashKey, hashField, hashValue); // 读取哈希中的二进制值 byte[] result = jedis.hget(hashKey, hashField); System.out.println(new String(result)); } } }
关键说明
- Jedis 4.x 里,
Jedis类实现了原BinaryJedis的所有二进制操作方法,包括字符串类的set(byte[], byte[])、get(byte[]),以及哈希类的hset(byte[], byte[], byte[])等,不需要额外切换类。 - 如果用连接池,
JedisPool获取的Jedis实例同样支持所有二进制操作,用法和单实例完全一致。
内容的提问来源于stack exchange,提问作者Oliver
相关产品推荐
相关产品推荐

