这里我们尝试将Protobuf和RPC结合在一起使用,通过 Protobuf来最终保证RPC的接口规范和安全。
Protobuf中最基本的数据单元是message,是类似Go语言中结构体的存在。在message中可以嵌套message或其他基础数据类型的成员。
$ protoc --go_out=. hello.proto
type String struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *String) Reset() {
*x = String{}
if protoimpl.UnsafeEnabled {
mi := &file_hello_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *String) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*String) ProtoMessage() {}
func (x *String) ProtoReflect() protoreflect.Message {
mi := &file_hello_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use String.ProtoReflect.Descriptor instead.
func (*String) Descriptor() ([]byte, []int) {
return file_hello_proto_rawDescGZIP(), []int{0}
}
func (x *String) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
此处隐藏了一些以xxx_为名字前缀的成员,ProtoMessage()方法表示这是一个实现了proto.Message接口的方法。此外,Protobuf还为每一个成员生成了一个Get方法,Get方法不仅可以处理空指针类型, 而且可以与Protobuf第二版的方法保持一致。
6. 基于新的String类型,我们可以重新实现HelloService服务:
type HelloService struct{}
func(p *HelloService) Hello(request *String, reply *String) error{
reply.Value = "hello:"+request.GetValue()
return nil
}
service HelloService{
rpc Hello (String) returns (String);
}
原文:https://www.cnblogs.com/pangqianjin/p/14618031.html