安装Protobuf
解压包,tar -xvf;
cd进目录,执行:./configure --prefix=/Users/mrzhang/workspace/tools/protobuf
make;
make check;
make install;
构建模板
指定3.0+版本
syntax = "proto3";
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;
}
生成protof文件:
protoc -I=src/main/resource/proto
--java_out=src/main/java src/main/resource/proto/protobuf.proto
引入依赖:
com.google.protobuf
protobuf-java
3.5.0
如果使用json,引入依赖:
com.google.protobuf
protobuf-java-util
3.5.0
构建对象并序列化放到redis
System.out.println("===== 构建一个GPS模型开始 =====");
Protobuf.gps_data.Builder gps_builder = Protobuf.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);
Protobuf.gps_data gps_data = gps_builder.build();
byte[] bytes = gps_data.toByteArray();
jedis.set("foo".getBytes(), bytes);
System.out.println("========");
bytes = jedis.get("foo".getBytes());
Protobuf.gps_data gd = null;
try {
gd = Protobuf.gps_data.parseFrom(bytes);
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
System.out.println("id: " + gd.getAltitude() + ", time: " + gd.getDataTime());
redis结果:
127.0.0.1:6379> get foo
"\bd\x1a\x132017-12-17 16:21:44!\xbaI\x0c\x02+\a^@)9\xb4\xc8v\xbe\x8fC@8\x01H\x01U\x9a\x99\xf1A"
序列化成Json
System.out.println("===== 使用gps 转成json对象开始 =====");
String jsonFormatM = "";
try {
jsonFormatM = JsonFormat.printer().print(gps_builder);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(jsonFormatM.toString());
System.out.println("json数据大小:" + jsonFormatM.getBytes().length);
System.out.println("===== 使用gps 转成json对象结束 =====");