一:环境安装
1 安装brew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
2 使用brew安装protobuf
brew install protobuf
3 查看protoc版本
protoc --version
4 查看protobuf版本
brew search protobuf
二:示例
gps_data.proto
syntax = "proto3";
option java_package = "com.dongwt.proto";
message gps_data {
int64 id = 1;
string terminalId = 2;
string dataTime = 3;
double lon = 4;
double lat = 5;
float speed = 6;
int32 altitude = 7;
int32 locType = 8;
int32 gpsStatus = 9;
float direction = 10;
int32 satellite = 11;
}
执行命令
protoc -I=src/main/resources/proto --java_out=src/main/java gps_data.proto
三:pom依赖(版本号序号protoc版本保持一致)
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.17.3</version>
</dependency>
四:单侧
public class TestGpsProtobuf {
public static void main(String[] args) {
System.out.println("===== 构建一个GPS模型开始 =====");
GpsData.gps_data.Builder gps_builder = GpsData.gps_data.newBuilder();
gps_builder.setAltitude(1);
gps_builder.setDataTime("2017-12-17 16:21:44");
gps_builder.setGpsStatus(1);
gps_builder.setLat(39.123);
gps_builder.setLon(120.112);
gps_builder.setDirection(30.2F);
gps_builder.setId(100L);
GpsData.gps_data gps_data = gps_builder.build();
System.out.println(gps_data.toString());
System.out.println("===== 构建GPS模型结束 =====");
System.out.println("===== gps Byte 开始=====");
for(byte b : gps_data.toByteArray()){
System.out.print(b);
}
System.out.println("\n" +"bytes长度" + gps_data.toByteString().size());
System.out.println("===== gps Byte 结束 =====");
System.out.println("===== 使用gps 反序列化生成对象开始 =====");
GpsData.gps_data gd =null;
try {
gd = GpsData.gps_data.parseFrom(gps_data.toByteArray());
}catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
System.out.print(gd.toString());
System.out.println("===== 使用gps 反序列化生成对象结束 =====");
}
}
网友评论