首页 > 代码库 > redis 序列化存入对象

redis 序列化存入对象

redis 序列化存入对象

 //序列化 
    public static byte [] serialize(Object obj){
        ObjectOutputStream obi=null;
        ByteArrayOutputStream bai=null;
        try {
            bai=new ByteArrayOutputStream();
            obi=new ObjectOutputStream(bai);
            obi.writeObject(obj);
            byte[] byt=bai.toByteArray();
            return byt;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    //反序列化
    public static Object unserizlize(byte[] byt){
        ObjectInputStream oii=null;
        ByteArrayInputStream bis=null;
        bis=new ByteArrayInputStream(byt);
        try {
            oii=new ObjectInputStream(bis);
            Object obj=oii.readObject();
            return obj;
        } catch (Exception e) {
            
            e.printStackTrace();
        }
    
        
        return null;
    }
    
    @Test
    public void testSerialize(){
        AuUser auUser = new AuUser();
        auUser.setId("1");
        auUser.setUsername("zs");
        auUser.setPassword("123");
        
        jedis.set("user".getBytes(), serialize(auUser));
        byte[] byt = jedis.get("user".getBytes());
        Object object = unserizlize(byt);
        if(object instanceof AuUser){
            AuUser user = (AuUser) object;
            System.out.println(user.getUsername());
            System.out.println(user.getPassword());
        }
    }

结果
技术分享

 

redis 序列化存入对象