Redis 存储自定义的数据类型

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值