Redis自带的基本类型的操作可以自行查阅资料,网上可以轻易找到很多的相关的资料。
存储自定义类型时需要进行序列化、反序列化。
1. Java示例代码
//定义需要存储的数据
StudentVo studentVo = newStudentVo();
studentVo.setId(student.getId());
studentVo.setApplyTeacherState(student.getApplyTeacherState());
studentVo.setBornDate(student.getBornDate());
studentVo.setHeadPic(student.getHeadPic());
studentVo.setIntroduce(student.getIntroduce());
studentVo.setIsTeacher(student.getIsTeacher());
studentVo.setRealName(student.getRealName());
studentVo.setNickName(student.getNickName());
studentVo.setPhoNum(student.getPhoNum());
//实例化一个新的jedis对象
jedis = new Jedis("your server IP ", 6379);
UUID uuid = UUID.randomUUID();
String jSession = uuid.toString();
//jSession是用户登录过程中产生的唯一标识
studentVo.setSessionId(jSession);
//SerializationUtil负责序列化与反序列化的类。
jedis.set(jSession.getBytes(), SerializationUtil.serialize(studentVo));
// 设置过期时间
jedis.expire(jSession, 3600);
//上面描述的是如何存储自定义类型,下面是如何使用
//如果登录系统之后,系统访问链接后面都会带着一个UUID作为唯一标识,
//sessionId是用户的唯一标识
byte[] bSession= jedis.get(sessionId.getBytes());
//通过反序列化就能够获取存储的数据
StudentVo student = (StudentVo)SerializationUtil.deserialize(bSession);
2. 序列化、反序列化代码
public classSerializationUtil {
//序列化
publicstatic 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;
}
//反序列化
publicstatic Object deserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
}
return null;
}
}
python 代码实现中序列化直接调用对象的 dump() 方法即可完成序列化。
参考: http://blog.csdn.net/Senior_lee/article/details/50642705