一、编写proto协议
当我们某一个字段可能出现多种不同类型,那么就可以使用oneof。对于网络传输中的一个响应,可能出现不同的结构。例如,response可能是文章列表(包含标题,正文,作者,日期等字段)、也有可能是一首歌(歌曲的byte,标题,作者信息等)。我们可以设计如下proto,使用protoc --cpp_out=. response.proto生成c++源代码,接下来写测试代码。
// response.proto
syntax="proto3";
message Response {
Header header = 1;
oneof payload {
ArticleResponse articleResponse = 2;
MusicResponse musicResponse = 3;
}
}
message Header {
string namespace = 1;
string name = 2;
string version = 3;
}
message ArticleResponse {
string title = 1;
string author = 2;
string date = 3;
}
message MusicResponse {
string title = 1;
string author = 2;
bytes data = 3;
}
二、测试代码
代码中,我尝试实现同时写入ArticleResponse和MusicResponse。使用g++ *.cc -o main -lprotobuf -std=c++11编译,可以看到结果只有article的返回有结果。
#include "response.pb.h"
#include <string>
using namespace std;
int main()
{
Response response;
Header *h = new Header;
h->set_namespace_("tensirfly.com");
h->set_name("music");
h->set_version("v1.0");
MusicResponse* mr = new MusicResponse;
mr->set_author("zjl");
mr->set_data("123");
mr->set_title("半岛铁盒");
ArticleResponse* ar = new ArticleResponse;
ar->set_author("my");
ar->set_date("2021年10月12日");
ar->set_title("红高粱家族");
response.set_allocated_header(h);
response.set_allocated_musicresponse(mr);
response.set_allocated_articleresponse(ar);
string str;
response.SerializePartialToString(&str);
cout<<"before: "<<sizeof(response)<<", after: "<<sizeof(str)<<endl;
Response dresponse;
dresponse.ParsePartialFromString(str);
cout<<"\nmusic header:"<<endl;
cout<<dresponse.header().namespace_()<<endl;
cout<<dresponse.header().name()<<endl;
cout<<dresponse.header().version()<<endl;
cout<<"\nmusic response:"<<endl;
cout<<"author: "<<dresponse.musicresponse().author()<<endl;
cout<<"title: "<<dresponse.musicresponse().title()<<endl;
cout<<"data: "<<dresponse.musicresponse().data()<<endl;
cout<<"\narticle response:"<<endl;
cout<<"author: "<<dresponse.articleresponse().author()<<endl;
cout<<"title: "<<dresponse.articleresponse().title()<<endl;
cout<<"date: "<<dresponse.articleresponse().date()<<endl;
return 0;
}
结果:
before: 40, after: 32
music header:
tensirfly.com
music
v1.0music response:
author:
title:
data:article response:
author: my
title: 红高粱家族
date: 2021年10月12日
三、总结
实际上,在使用oneof的时候,当给oneof多个字段设置时,会按照代码中的初始化顺序,返回最后一个初始化字段的值(进行set),其他值都不会生效。只设置一个值的时候才能得到正确的结果。当我们我们的系统越来越完善,响应类型也越来越大奥,那我们的请求体的大小会不会变十分庞大呢?实际上不会,因为oneof中的字段在set的时候一次只会初始化一个字段。实际大小有多大各位看官可以阅读proto生成的对象源码研究下,也欢迎直接在评论区解答~