在调用其他服务时,我应该重用 HTTP 服务器中的上下文对象吗?

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

Should I reuse context object in http server when calling other service?

问题

我正在使用net/http包开发一个服务器应用程序。
每当有请求到达时,net/http包会读取请求并创建一个http.Request对象。
我的服务器需要调用AWS DynamoDB来处理每个请求,在调用DynamoDB的QueryWithContext函数时,我将上下文对象传递给http.Request对象,类似于这样:

ctx := request.Context()
ctx := context.WithValue(ctx, myKey, myVal)

input := &dynamodb.QueryInput{
   ....
}

result, err := dbclient.QueryWithContext(ctx, input)

最近我看到一些来自QueryWithContextcontext canceled错误,我在想这可能是因为上下文对象被重用了,而且请求被取消了,所以对DynamoDB的服务调用也被取消了?

在调用另一个服务(比如DynamoDB)时,我应该重用上下文对象还是总是创建一个新的对象?谢谢。

英文:

I am developing a server application with the net/http package.
Everytime a request arrives, the net/http package reads the request and create a http.Request object.
My server needs to call AWS DynamoDB to serve every request, when calling DynamoDB's QueryWithContext function, I pass the context object in http.Request object, something like this:

ctx := request.Context()
ctx := context.WithValue(ctx, myKey, myVal)

input := &dynamodb.QueryInput{
   ....
}

result, err := dbclient.QueryWithContext(ctx, input)

Recently I saw several context canceled errors returned from QueryWithContext, I am thinking it might because the context object is reused and somehow the request is canceled so service call to DynamoDB also got canceled?

Should I reuse the context object when calling another service (like DynamoDB) or should I always create a new one? Thanks.

答案1

得分: 2

你好!根据你的问题,是否应该在调用另一个服务(如DynamoDB)时重用上下文对象,还是应该始终创建一个新的对象,这取决于你的需求。

如果你希望DynamoDB请求与请求绑定在一起,那么可以重用上下文对象。这意味着,如果HTTP请求被取消,DynamoDB请求是否应该继续执行还是中止,取决于你的需求。

英文:

> Should I reuse the context object when calling another service (like DynamoDB) or should I always create a new one? Thanks.

That depends.

Do you want the DynamoDB requests to be tied to the request, or not?

In other words, if the HTTP request is cancelled, should the DynamoDB requst continue, or abort?

huangapple
  • 本文由 发表于 2022年9月22日 17:10:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/73812049.html
匿名

发表评论

匿名网友

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

确定