Jedis 操作redis 序列化存储对象
时间:2021-11-10 作者:匿名
在Jedis开发中,我们很多时候希望直接把一个对象放到Redis中,然后在需要的时候取出来。Redis的key和value都支持二进制安全的字符串,存储Java对象不是问题,下面我们看一下如何来实现。
1要存储的对象
现在写一个很土的Java Bean,包含两个字段,id和name,类名叫做Person。为了实现序列化需求,该类实现Serializable接口。
public class Person implements Serializable { private int id; private String name; public Person(int id, String name) { 域名 = id; 域名 = name; } public int getId() { return id; } public String getName() { return name; } }
2序列化、反序列化
写一个序列化工具类,来提供对象的序列化和饭序列化的工作。代码如下:
public class SerializeUtil { public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { //序列化 baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); 域名eObject(object); byte[] bytes = 域名teArray(); return bytes; } catch (Exception e) { } return null; } public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { //反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return 域名Object(); } catch (Exception e) { } return null; } }
3写对象
将Person对象写入Redis中:
public void setObject() { Person person = new Person(100, "alan"); 域名("person:100".getBytes(), 域名alize(person)); person = new Person(101, "bruce"); 域名("person:101".getBytes(), 域名alize(person)); }
运行上面代码之后,我们到命令行窗口中读取该对象,看看有没有写入成功:
redis 127.0.0.1:6379> get person:100
“\\xac\\xed\\x00\\x05sr\\x00\\域名on\\x05\\xf4\\x8d9A\\xf4`\\xb0\\x02\\x00\\x02I\\x00\\x02idL\\x00\\x04namet\\x00\\x12Ljava/lang/String;xp\\x00\\x00\\x00dt\\x00\\x04alan”
可以取到序列化之后的值。
4取对象
用Jedis获取对象:
public Person getObject(int id) { byte[] person = 域名(("person:" + id).getBytes()); return (Person) 域名rialize(person); }
测试一下上一步存入的两个对象:
Person person = 域名bject(100); 域名tln(域名d()); 域名tln(域名ame()); person = 域名bject(101); 域名tln(域名d()); 域名tln(域名ame());
Java控制台输入:
100
alan
101
bruce
由此可见,序列化对象在Redis中存取正确。
方法测试可行。