Grpc协议一点知识点

grpc是应用层协议,protobuf可以帮助我们生成和语言相关的消息实体,通过这些生成的消息实体,我们在java的使用中就能够像是自己创建的类一样去调用它

message SearchRequest {
  required string query = 1;
  optional int32 page_number = 2;
  optional int32 result_per_page = 3;
}

这是一个简单的消息体,官方文档上的代码,从名字上我们能看出这是一个请求的实体, 规则、类型、字段名、默认值

Assigning Field Numbers

query 、page_number 、result_per_page是我们实体的属性值,也就是一个变量,那变量为什么会有要给默认值呢?从官方的解释中我们能看到这样一段话:

 As you can see, each field in the message definition has a unique number. These numbers are used to identify your fields

 in the message binary format, and should not be changed once your message type is in use. Field numbers in the range 1
through 15 take one byte to encode, including the field number and the field's type (you can find out more about this in 
Protocol Buffer Encoding). Field numbers in the range 16 through 2047 take two bytes. So you should reserve the field numbers 1
through 15 for very frequently occurring message elements. Remember to leave some room for frequently occurring elements that
might be added in the future.

大概的意思就是:在我们设置数值型的字段时,我们要给他一个唯一值,这些唯一值的作用是在消息二进制转化时标识你的字段,一旦定义了就不能在改了,因为会导致序列化的时候出现错误,原来你给字段a默认值1,
现在你把字段b也默认值为1了,如果客户端没有重新发布,还是用老版本的代码,这时候,客户端传的a值,在服务端都转化成b了,不同的默认值范围会占用不同的字节,在定义默认值时,适当的留一些空间

Specifying Field Rules指定字段规则

rule就是一个validate,校验字段是否为空,有三种类型的规则:

required

optional

repeated

You should be very careful about marking fields as required. If at some point you wish to stop writing or sending a required field, it will be 
problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject
or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers
at Google have come to the conclusion that using required does more harm than good; they prefer to use only optional and repeated. However, this view
is not universal.
在定义
required时一定要非常小心谨慎,因为一旦客户端不传这个字段,服务端还没有更新,这个时候就会拒绝请求
Combining Messages leads to bloat While multiple message types (such as message, enum, and service) can be defined in a single .proto file, it can also lead to dependency bloat
when large numbers of messages with varying dependencies are defined in a single file.
It's recommended to include as few message types per .proto file as possible.
最好不要在一个proto文件中定义太多的消息体,这样会导致文件过于臃肿




posted @ 2021-12-07 17:36  骚年  阅读(371)  评论(0)    收藏  举报