Protocol Buffer是一种轻便高效的结构化数据存储格式,可以用于结构化数据序列化和反序列化,适合做RPC的数据交换格式。具有平台无关性、可扩展性等。
如何使用protocol buffer?(java)
1) 编写.proto文件
代码如下:
Student.proto
package tutorial;
option java_package = "org.example";
option java_outer_classname = "StudentProtos";
message Student{
required int32 ID = 1;
required string name = 2;
required string sex=3;
message StudentPhone{
required string number = 1;
optional int32 type = 2;
}
repeated StudentPhone sp=4;
}
2) Protoc命令编译成类文件
然后进入此目录下执行指令
Protoc –java_out=./ ./student.proto
生成文件目录为
如果没有安装protoc编译工具,则执行下列命令安装(ubuntu系统):
Sudo apt install protobuf-compiler
3) 调用2)生成的类,实例化。
调用类实例:
package org.example;
import org.example.StudentProtos.Student;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Arrays;
public class TestProtocol {
public static void main(String[] args) {
Student student1 = Student.newBuilder().setName("lily").setID(123).setSex("woman")
.addSp(Student.StudentPhone.newBuilder().setNumber("1321566666").setType(1))
.addSp(Student.StudentPhone.newBuilder().setNumber("13345627777").setType(2)).build();
try{
FileOutputStream output = new FileOutputStream("example.txt");
student1.writeTo(output);
output.close();
}catch (Exception e){
System.out.println("write error");
}
try{
FileInputStream input = new FileInputStream("example.txt");
Student st = Student.parseFrom(input);
System.out.println("st2" + st);
}catch (Exception e){
System.out.println("read error");
}
}
}
Protocol Buffer代码分析
1) 指定字段类型
2) 分配标识号
3) 指定字段规则
Required:该值是必须要设置的
Optional:消息格式中该字段可以有0或1个值
Repeated:这种字段可以重复多次,重复的顺序会被保留。
4) 定义服务
格式为:
service SearchService{
rpc Search (SearchRequest) returns (SearchResponse);
}
Protoc命令格式: