protobuf

maven导包

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.baidu</groupId>
<artifactId>jprotobuf</artifactId>
<version>2.2.0</version>
</dependency>

注解

@Protobuf 修饰字段
@ProtobufClass 修饰类,支持默认字段识别能力。相等于所有字段都用@Protobuf修饰了。

使用jprotobuf API进行序列化与反序列化操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Codec<SimpleTypeTest> simpleTypeCodec = ProtobufProxy
.create(SimpleTypeTest.class);

SimpleTypeTest stt = new SimpleTypeTest();
stt.name = "abc";
stt.setValue(100);
try {
// 序列化
byte[] bb = simpleTypeCodec.encode(stt);
// 反序列化
SimpleTypeTest newStt = simpleTypeCodec.decode(bb);
} catch (IOException e) {
e.printStackTrace();
}

由注解对象动态生成Protobuf的IDL描述文件内容

JProtobuf提供一个非常实用的功能,可以动态生成Protobuf的IDL描述文件内容

//返回的内容即为 Protobuf的IDL描述文件
String code = ProtobufIDLGenerator.getIDL(SimpleTypeTest.class);