Thrift序列化和反序列化处理代码(java版)

好多网上介绍的thrift都是基于rpc的服务端客户端的例子,看了下c++版本的序列化处理,摸索了一下,找到序列化、反序列化的处理方法,记录一下。


// 内存级缓冲,默认32长度,自动增加
TMemoryBuffer mb0 = new TMemoryBuffer(32);
TProtocol prot0 = new org.apache.thrift.protocol.TCompactProtocol(mb0);

TMemoryBuffer mb1 = new TMemoryBuffer(32);
TProtocol prot1 = new org.apache.thrift.protocol.TBinaryProtocol(mb1);

TMemoryBuffer mb2 = new TMemoryBuffer(32);
TProtocol prot2 = new org.apache.thrift.protocol.TJSONProtocol(mb2);

// 传输消息对象
RequestMessage msg = new RequestMessage();
msg.setMessage("abcdefghjklfadfadfadfadloiue");
msg.setKey("key");
// 序列化处理
msg.write(prot0);
msg.write(prot1);
msg.write(prot2);
System.out.println("序列化长度Compact:" + mb0.length());
System.out.println("序列化长度Binary:" + mb1.length());
System.out.println("序列化长度JSON:" + mb2.length());

// 反序列化处理
byte[] data = mb1.getArray(); // 接收的字节
RequestMessage msg1 = new RequestMessage();
TMemoryBuffer tmb = new TMemoryBuffer(32);
tmb.write(data);
TProtocol tp = new org.apache.thrift.protocol.TBinaryProtocol(tmb);
msg1.read(tp);
System.out.println(msg1.getMessage());


执行:

序列化长度Compact:36
序列化长度Binary:46
序列化长度JSON:62
abcdefghjklfadfadfadfadloiue



你可能感兴趣的:(RPC&序列化)