1. 程式人生 > >Redis 儲存自定義的資料型別

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() 方法即可完成序列化。