加入收藏 | 设为首页 | 会员中心 | 我要投稿 南通站长网 (https://www.0513zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

聊聊为何IDL 只能扩展字段而非修改

发布时间:2021-12-27 13:08:16 所属栏目:大数据 来源:互联网
导读:前几年业界流行使用 thrift, 比如滴滴。这几年 grpc 越来越流行,很多开源框架也集成了,我司大部分服务都同时开放 grpc 和 http 接口 相比于传统的 http1 + json 组合,这两种技术都用到了 IDL, 即 Interface description language 接口描述语言,相当于增加
前几年业界流行使用 thrift, 比如滴滴。这几年 grpc 越来越流行,很多开源框架也集成了,我司大部分服务都同时开放 grpc 和 http 接口
 
相比于传统的 http1 + json 组合,这两种技术都用到了 IDL, 即 Interface description language 接口描述语言,相当于增加了 endpoint schema 约束,不同语言只需要一份相同的 IDL 文件即可生成接口代码。
 
很多人喜欢问:proto buf 与 json 比起来有哪些优势?比较经典的面试题
 
IDL 文件管理每个公司不一样,有的保存在单独 gitlab 库,有的是 mono repo 大仓库。当业务变更时,IDL 文件经常需要修改,很多新手总是容易踩坑,本文聊聊 grpc proto 变更时的兼容问题,核心只有一条:对扩展开放,对修改关闭,永远只增加字段而不修改
 
测试修改兼容性
本文测试使用 grpc-go example 官方用例,感兴趣自查
 
syntax = "proto3";
 
option go_package = "google.golang.org/grpc/examples/helloworld/helloworld";
package helloworld;
 
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}
 
// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}
 
// The response message containing the greetings
message HelloReply {
  string message = 1;
  string additional = 2;
  int32 age = 3;
  int64 id = 4;
}
每次修改后使用 protoc 重新生成代码
 
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative helloworld/helloworld.proto
Server 每次接受请求后,返回 HelloReply 结构体
 
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
 log.Printf("Received: %v", in.GetName())
 return &pb.HelloReply{
  Message:    "Hello addidional " + in.GetName(),
  Additional: "this is addidional field",
  Age:        10,
  Id:         12345,
 }, nil
}
Client 每次只打印 Server 返回的结果
 
修改字段编号
将 HelloReply 结构体字段 age 编号变成 12, 然后 server 使用新生成的 IDL 库,client 使用旧版本
 
zerun.dong$ ./greeter_client
......
2021/12/08 22:23:38 Greeting: {
 "message": "Hello addidional world",
 "additional": "this is addidional field",
 "id": 12345
}
可以看到 client 没有读到 age 字段,因为 IDL 是根据序号传输的,client 读不到 seq 3, 所以修改序号不兼容
 
修改字段 name
修改 HelloReploy 字段 id, 变成 score 类型和序号不变
 
// The response message containing the greetings
message HelloReply {
  string message = 1;
  string additional = 2;
  int32 age = 3;
  int64 score = 4;
}
重新编译 server, 并用旧版本 client 访问
 
zerun.dong$ ./greeter_client
......
2021/12/08 22:29:18 Greeting: {
 "message": "Hello addidional world",
 "additional": "this is addidional field",
 "age": 10,
 "id": 12345
}
可以看到,虽然修改了字段名,但是 client 仍然读到了正确的值 12345, 如果字段含义不变,那么只修改名称是兼容的。

(编辑:南通站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读