Protobuf基本使用

本文介绍了如何在Java环境中安装和使用Protobuf,包括下载Protobuf、配置环境变量、使用Maven构建protobuf项目、编写.proto文件、使用protoc.exe编译及进行简单的测试。通过示例展示了如何将protobuf消息类型转换为Java类并进行操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、 安装Protobuf
去Protobuf的GitHub下载,解压。
如果你是Windows环境,则还要下载protoc.exe
把protoc.exe放在Protobuf安装目录下的src里。

二、 配置环境变量
编辑系统变量Path,添加Protoc.exe的存放目录。

三、Eclipse新建项目
我使用maven构建protobuf项目,方便引入依赖。
在项目根目录创建proto文件夹,存放proto文件。
pom.xml如下

com.google.protobuf
protobuf-java
3.0

项目结构如下:

在这里插入图片描述

四、编写.proto文件
在proto文件夹下编写student-entity.proto
option java_outer_classname =“StudentEntity”;//生成的数据访问类的类名
message Student {
required int32 id = 1;//同上
required string name = 2;//必须字段,在后面的使用中必须为该段设置值
optional string email = 3;//可选字段,在后面的使用中可以自由决定是否为该字段设置值
}

五、使用protoc.exe编译成java类

有两种方法:

  1. 使用Java Rumtime执行cmd命令
  2. 直接打开cmd运行命令也行。
    @Test
    publicvoid test() {
    String protoFile =“student-entity.proto”;//
    String strCmd = “D:/protobuf-master/src/protoc.exe -I=./proto–java_out=./src/main/java ./proto/”+ protoFile;
    try {
    Runtime.getRuntime().exec(strCmd);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

命令格式如下:

在这里插入图片描述

上述代码的生成strCmd编写与命令一致。
生成的StudentEntity.java类。

六、测试
public class Test {
public static void main(String[] args) throws IOException {
//模拟将对象转成byte[],方便传输
StudentEntity.Student.Builder builder = StudentEntity.Student.newBuilder();
builder.setId(1);
builder.setName(“itcast”);
builder.setEmail("xxx@qq.com");
StudentEntity.Student student= builder.build();
System.out.println(“before :”+ student.toString());

   System.out.println("=========== Byte==========");
   for(byte b : student.toByteArray()){
       System.out.print(b);
   }
   System.out.println(student.toByteString());
   System.out.println("================================");

   //模拟接收Byte[],反序列化成Person类
   byte[] byteArray =person.toByteArray();
   Student s2 = Student.parseFrom(byteArray);
   System.out.println("after :" +s2.toString());
}

}

七、查看控制台输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值