英文:
Should I send new or old Context object to 3rd party gRPC API within my own gRPC server?
问题
我们有一个用Go语言编写的gRPC服务器。对于其中一个RPC,我们从Google Maps gRPC API请求数据。一旦我们从Google Maps RPC收到响应,我们会进行一些计算,并将响应返回给封闭的RPC(由我们的服务器定义)。
当在我们的服务器上调用RPC时,自然会收到一个Context对象。
我的问题是:我们应该将相同的Context对象传递给Google Maps RPC吗?还是应该创建一个新的Context对象(使用context.Background()
),然后将其传递给Google Maps API?
英文:
We have a gRPC server written in golang. For one of the RPCs, we request data from the Google Maps gRPC API. Once we receive a response from the Google Maps RPC, we do some calculations and return a response to the enclosing RPC (defined by our server).
Naturally, we receive a Context object when the RPC is called on our server.
My question is: Should we pass this same Context object to the Google Maps RPC? Or, should we instead create a new Context object (using context.Background()
), and then pass this to the Google Maps API?
答案1
得分: 2
据我了解,一个上下文只在一个RPC的生命周期内有效,而且只能对应一个RPC。因此,一旦我们意识到要进行完全不同的RPC调用,就应该创建一个新的上下文。然而,新上下文的元数据可能受到当前上下文元数据的启发。在这里,RPC可以被视为Android中的单个活动/服务/广播的类比。
英文:
As far as i have figured, 1 context is valid for the life cycle of 1 and only 1 rpc.
So as soon as we realize that we are about to make a whole different rpc call, we should make a new context.
However, The metadata of the new context may be inspired by the metadata of the current context.
An RPC here may be considered analogous to a single activity/service/broadcast in android.
答案2
得分: 2
你收到的上下文中包含了取消和超时信息,所以最好使用相同的上下文来进行新的RPC调用。否则,你需要手动传递这些信号。
关于元数据,接收到的上下文中的元数据不会自动转发到新的RPC调用中,请参考以下链接:
https://github.com/grpc/grpc-go/issues/1148
https://github.com/grpc/grpc-go/pull/1157
英文:
The context you received contains the cancellation and timeout, so it would be good to use the same context to make the new RPC. Otherwise you need to manually pass these signals.
A side on the metadata, metadata in the received context will not be automatically forwarded to the new RPC, see:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论