背景
客户端更新proto,新增message字段,探索新增字段的数据类型和标签对服务端反序列化数据的影响
结论
- 新增字段数据类型与服务端相同标签数据类型:
- 不同:无法获取数据,但是不报错
- 相同:能够获取到数据,但数据不是真正要获取的
pb中序列化和反序列化数据时,对message字段只关注它的数据类型和标签,不关注定义的名称
原始数据
demo2_1.proto
syntax = "proto2";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
demo2_2.proto
syntax = "proto2";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
write.cc
#include <iostream>
#include <fstream>
#include "demo2_1.pb.h"
int main(int argc, const char* argv[])
{
// 创建AddressBook Person 对象
Person person;
// 设置person对象属性值
person.set_name("zhangsan");
person.set_id(1001);
person.set_email("zhangsan@qq.com");
// 序列化为二进制流并写入文件中
std::fstream output("msg", std::ios::out | std::ios::trunc | std::ios::binary);
if (!person.SerializeToOstream(&output)) {
std::cerr << "Failed to serialize." << std::endl;
return -1;
}
return 0;
}
read.cc
#include <iostream>
#include <fstream>
#include "demo2_2.pb.h"
int main(int argc, const char* argv[])
{
// 创建AddressBook Person 对象
Person person;
// Read the existing address book.
std::fstream input("msg", std::ios::in | std::ios::binary);
if (!person.ParseFromIstream(&input)) {
std::cerr << "Failed to parse." << std::endl;
return -1;
}
std::cout << "*****************************" << std::endl;
std::cout << "id: " << person.id() << std::endl;
std::cout << "name: " << person.name() << std::endl;
std::cout << "email: " << person.email() << std::endl;
std::cout << "*****************************" << std::endl;
return 0;
}
编译(pb2.5.0) 结果:
*****************************
id: 1001
name: zhangsan
email: zhangsan@qq.com
*****************************
测试1
修改demo2_1.proto如下:
syntax = "proto2";
message Person {
required string name = 1;
required int32 id = 2;
optional int32 mobile = 3;
optional string email = 4;
}
demo2_2.proto保持不变,结果如下:
*****************************
id: 1001
name: zhangsan
email:
*****************************
测试2
修改demo2_1.proto如下:
syntax = "proto2";
message Person {
required string name = 1;
required int32 id = 2;
optional string mobile = 3;
optional string email = 4;
}
demo2_2.proto保持不变,结果如下:
*****************************
id: 1001
name: zhangsan
email: 10010
*****************************