利用protobuf序列化对象

作者: 大华夏 | 来源:发表于2017-07-02 20:15 被阅读64次

序列化原理

给protobuf协议对象加一个外壳,通过重写private void writeObject(java.io.ObjectOutputStream out) throws IOException 和 private void readObject(java.io.ObjectInputStream in)throws IOException, ClassNotFoundException 方法,完成序列化和反序列化

protobuf协议对象外壳定义


import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.google.protobuf.GeneratedMessageLite;
/**
 * 加上外壳的protobuf协议实体封装
 * @author 
 *
 * @param <T>
 */
public class Entity<T extends GeneratedMessageLite> implements Serializable {

    private static final long serialVersionUID = 6551693082927216000L;
    //被封装的protobuf协议对象
    private T data_;

    public Entity(T data_){
        this.data_ = data_;
    }
    public T getData_() {
        return data_;
    }
    
    private void writeObject(java.io.ObjectOutputStream out) throws IOException{
        //写入类名称,目的是为了在读取的时候对应到具体的protobuf协议对象
        writeClassName(out);
        out.write(data_.toByteArray());
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void readObject(java.io.ObjectInputStream in)throws IOException, ClassNotFoundException{
        //从输入流中先读取类的名称
        Class clazz = Class.forName(readClazzName(in));
        
        Method method;
        //利用反射机制获取parseFrom方法来读取数据
        try {
            method = clazz.getMethod("parseFrom", java.io.InputStream.class);
            data_ = (T)method.invoke(null, in);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    /**
     * 往输出流中写入类名
     * @param out
     * @throws IOException
     */
    private void writeClassName(java.io.ObjectOutputStream out) throws IOException{
        byte[] clazzNameBytes = data_.getClass().getName().getBytes();
        out.writeShort(clazzNameBytes.length);
        out.write(clazzNameBytes);
    }
    /**
     * 从输入流中读取类名
     * @param in
     * @return
     * @throws IOException
     */
    private String readClazzName(java.io.ObjectInputStream in) throws IOException{
        int len = in.readShort();
        byte[] bytes = new byte[len];
        in.read(bytes);
        return new String(bytes);
    }   
}

测试用例

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Assert;
import org.junit.Test;

import com.yaowan.protobuf.commons.CommonsProto;
import com.yaowan.protobuf.commons.CommonsProto.Player;
import com.yaowan.study.topic.serializable.Entity;

public class ProtoSerializableUseCase {

    @Test
    public void testSerializable() throws IOException, ClassNotFoundException{
        //生成一个protobuf协议对象
        CommonsProto.Player.Builder playerBuilder = CommonsProto.Player.newBuilder();
        playerBuilder.setId(1111);
        playerBuilder.setNickname("Hello_CHINA");
        playerBuilder.setOpenid("1234-5678-9012");

        //加上外壳
        Entity<Player> entity = new Entity<Player>(playerBuilder.build());
        
        //序列化对象
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(entity);
        objectOutputStream.flush();
        objectOutputStream.close(); 
    
        byte[] bytes = byteArrayOutputStream.toByteArray();        
        //反序列化
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Entity<Player> entity2 = (Entity<Player>) objectInputStream.readObject();
        objectInputStream.close();
        Assert.assertEquals(entity.getData_().getId(), entity2.getData_().getId());
        Assert.assertEquals(entity.getData_().getNickname(), entity2.getData_().getNickname());
        Assert.assertEquals(entity.getData_().getOpenid(), entity2.getData_().getOpenid());
        
        System.out.println(entity2.getData_().getNickname()+","+entity2.getData_().getOpenid()+","+entity2.getData_().getId());
        
    }
}

相关文章

  • 利用protobuf序列化对象

    序列化原理 给protobuf协议对象加一个外壳,通过重写private void writeObject(jav...

  • 序列化和反序列化

    proto序列化和反序列化类 序列化是将我们的protobuf类对象转换成字节数组的方法 网络底层我们从服务器获取...

  • Go语言 ProtoBuf 序列化和反序列化

    Protobuf 是Google开发的一个网络通信协议,提供了高效率的序列化和反序列化机制,序列化就是把对象转换成...

  • NetModel

    using System;using ProtoBuf; //添加特性,表示可以被ProtoBuf工具序列化[Pr...

  • 转载:Protobuf在Cmake中的正确使用

    Protobuf在Cmake中的正确使用 Protobuf是google开发的一个序列化和反序列化的协议库,我们可...

  • Protobuf的序列化与反序列化

    Protobuf的序列化与反序列化 proto.proto文件内容 Java 实现 序列化 反序列化 GO 实现 ...

  • protobuf-java的使用

    protobuf是谷歌定义的一种语言无关、平台无关的数据交换格式,可以将对象序列化为字节数组、将字节数组反序列化为...

  • FDBUS编译和使用

    源码下载 下载和编译protobuf fdbus的序列化使用了protobuf。 下载和编译fdbus 编译fdb...

  • ProtoBuf 懒人插件

    插件由来 之前在学习GRPC 微服务开发时,学习到了ProtoBuf 这个序列化协议,但是ProtoBuf 编译的...

  • 深入 ProtoBuf - 反射原理解析

    在介绍了 ProtoBuf 序列化原理之后,本文介绍 ProtoBuf 的反射技术原理。 反射技术简介 对于反射大...

网友评论

    本文标题:利用protobuf序列化对象

    本文链接:https://www.haomeiwen.com/subject/vfrocxtx.html