Jedis存储Java对象 - (Java序列化为byte数组方式)
//redis set对象
public class Person implements Serializable {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
//序列化工具类
public class SerializeUtil {
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
//序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
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 ois.readObject();
} catch (Exception e) {
}
return null;
}
}
//写对象
public void setObject() {
Person person = new Person(100, "alan");
jedis.set("person:100".getBytes(), SerializeUtil.serialize(person));
person = new Person(101, "bruce");
jedis.set("person:101".getBytes(), SerializeUtil.serialize(person));
}
//取对象
public Person getObject(int id) {
byte[] person = jedis.get(("person:" + id).getBytes());
return (Person) SerializeUtil.unserialize(person);
}
评论
发表评论
|
|