Par*_*hwa 12 go protocol-buffers grpc-go
最近,grpc-go 引入了 mustEmbedUnimplemented*** 方法。它用于向前兼容。
简单来说,我无法理解它是如何提供帮助的,以及在没有它的情况下我们面临哪些问题?现在在我的结构中,我使用添加以下语句,但是,我不知道为什么...
type server struct {
pdfpb.UnimplementedGreetServiceServer
}
Run Code Online (Sandbox Code Playgroud)
在 Github 问题 - https://github.com/grpc/grpc-go/issues/3669 中,他们对此进行了辩论,有人可以简单地解释一下它是如何提供帮助的,以及在没有它的情况下我们面临哪些问题?
bla*_*een 22
此错误来自较新版本的protoc-gen-grpc-go编译器。服务器实现现在必须向前兼容。
在此更改之前,每当您注册服务器实现时,您都会执行以下操作:
pb.RegisterFooBarServiceServer(
server,
&FooBarServer{}, // or whatever you use to construct the server impl
)
Run Code Online (Sandbox Code Playgroud)
如果您的服务器缺少一些方法实现,这将导致编译时错误。
使用较新的原始编译器版本,前向兼容性变为 opt-out,这意味着两件事:
您现在必须嵌入UnimplementedFooBarServiceServer,如错误消息所示。正如我所说,当您没有显式实现新方法时,这不会产生编译器错误(这就是前向兼容性的含义)。codes.Unimplemented不过,如果您尝试调用您没有(或忘记)显式实现的 RPC,则会导致运行时错误。
UnsafeFooBarServiceServer您仍然可以通过嵌入(带前缀)来选择退出向前兼容性Unsafe。该接口只是声明了mustEmbedUnimplementedFooBarServiceServer()使问题中的错误消失的方法,如果您没有显式实现新的处理程序,则不会放弃编译器错误。
例如:
// Implements the grpc FooBarServiceServer
type FooBarService struct {
grpc.UnsafeFooBarServiceServer // consciously opt-out of forward compatibility
// other fields
}
Run Code Online (Sandbox Code Playgroud)
protoc-gen-grpc-go您还可以通过在插件(源)上设置选项来生成没有向前兼容性的代码:
pb.RegisterFooBarServiceServer(
server,
&FooBarServer{}, // or whatever you use to construct the server impl
)
Run Code Online (Sandbox Code Playgroud)
注意选项:.后面的--go-grpc_out选项用于设置路径元素。
那是非常基本的。
UnimplementedGreetServiceServer 是一个包含所有已实现方法的结构。当我添加 pdfpb.UnimplementedGreetServiceServer 时,我可以调用 UnimplementedGreetServiceServer 定义的方法。
就是这样,如果我在 proto 文件中添加更多 RPC 服务,那么我不需要添加所有导致向前兼容性的 RPC 方法。
演示代码可在https://github.com/parthw/fun-coding/tree/main/golang/understanding-grpc-change 获得
对于仍然遇到Github IssuemustEmbededUnimplementedServiceServer上建议的问题的任何人。最好的解决方案就是更新您的 ServerStruct。
前任。
type AuthenticationServiceServer struct {
}
Run Code Online (Sandbox Code Playgroud)
到。
type AuthenticationServiceServer struct {
service.UnimplementedAuthenticationServiceServer
}
Run Code Online (Sandbox Code Playgroud)
这将解决执行此操作时 Go 抛出的异常。
grpcService.RegisterAuthenticationServiceServer(grpcServer, controller.AuthenticationServiceServer{})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2828 次 |
| 最近记录: |