专业的编程技术博客社区

网站首页 > 博客文章 正文

Google Protobuf 学习笔记(google protocol buffer)

baijin 2024-08-27 11:09:28 博客文章 8 ℃ 0 评论

什么是protobuf

protobuf全称Google Protocol Buffers,是google开发的的一套用于数据存储,网络通信时用于协议编解码的工具库。protobuf是基于二进制的。

主要用于数据存储、传输协议格式等场合。

使用protobuf:

protobuf的使用很简单,开发人员按照一定的语法定义结构化的消息格式,然后用自带的编译工具,工具将自动生成相关的类,官方支持java、c++、python语言环境。

proto文件的编写也有自己的语法规则:

定义一个消息(message)类型

标量值类型

可选的(optional)字段以及默认值

枚举

使用其他消息类型

嵌套类型

更新一个消息类型

扩展

包(package)

定义服务(service)

选项(option)

生成访问类

首先:编写proto文件:

option java_package = "com.vince.im.protocol";

option java_outer_classname = "BaseProtocol";

message SNMessage {

optional string protocol = 1;

required string version = 2;

required string operation = 3;

message Member {

required string id = 1;

optional string name = 2;

}

message Data {

optional string type = 1;

optional string auth = 2;

optional string from = 3;

optional string to = 4;

optional string sender = 5;

optional string sendate = 6;

optional string conent = 7;

optional string media = 8;

optional string filename = 9;

repeated Member members = 10;

}

repeated Data data = 4;

}

其次:

protoc.exe --java_out=./src ./Message.proto > out.txt

结果生成了com.vince.im.protocol.BaseProtocol类。

序列化:

BaseProtocol.SNMessage.Member.Builder m = BaseProtocol.SNMessage.Member.newBuilder();

m.setId("13075694");

m.setName("Vince");

BaseProtocol.SNMessage.Data.Builder d = BaseProtocol.SNMessage.Data.newBuilder();

d.setAuth("123qweasd");

d.setFilename("beauty");

d.setFrom("13075694");

d.setTo("13075695");

d.setMedia("image");

d.setConent("hello world test");

d.setSendate("2014-09-09-09:53");

d.setSender("vince");

d.setType("text");

d.addMembers(m);

BaseProtocol.SNMessage.Builder snmessage = BaseProtocol.SNMessage.newBuilder();

snmessage.setProtocol("snchat");

snmessage.setVersion("1.0.0");

snmessage.setOperation("1000");

snmessage.addData(d);

BaseProtocol.SNMessage s = snmessage.build();

byte[] data = s.toByteArray()

反序列化:

protocol: "snchat"

version: "1.0.0"

operation: "1000"

data {

type: "text"

auth: "123qweasd"

from: "13075694"

to: "13075695"

sender: "vince"

sendate: "2014-09-09-09:53"

conent: "hello world test"

media: "image"

filename: "beauty"

members {

id: "13075694"

name: "Vince"

}

}

补充:序列化指将对象转换成二进制数据,反序列化是指将二进制数据转换成对象。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表