Protocol Buffer 简介

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命令格式:

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值