Should I send new or old Context object to 3rd party gRPC API within my own gRPC server?

huangapple go评论74阅读模式
英文:

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:

https://github.com/grpc/grpc-go/issues/1148

https://github.com/grpc/grpc-go/pull/1157

huangapple
  • 本文由 发表于 2017年6月22日 20:30:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/44699463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定