【发布时间】:2020-05-05 23:23:40
【问题描述】:
official Go documentation on the datastore package(GCP 数据存储服务的客户端库)具有以下代码 sn-p 用于演示:
type Entity struct {
Value string
}
func main() {
ctx := context.Background()
// Create a datastore client. In a typical application, you would create
// a single client which is reused for every datastore operation.
dsClient, err := datastore.NewClient(ctx, "my-project")
if err != nil {
// Handle error.
}
k := datastore.NameKey("Entity", "stringID", nil)
e := new(Entity)
if err := dsClient.Get(ctx, k, e); err != nil {
// Handle error.
}
old := e.Value
e.Value = "Hello World!"
if _, err := dsClient.Put(ctx, k, e); err != nil {
// Handle error.
}
fmt.Printf("Updated value from %q to %q\n", old, e.Value)
}
正如大家所见,它指出datastore.Client 在理想情况下应该只在应用程序中实例化一次。现在考虑到datastore.NewClient 函数需要一个context.Context 对象,这是否意味着它应该只在每个HTTP 请求中实例化一次,还是可以安全地使用context.Background() 对象在全局范围内实例化一次?
每个操作都需要一个context.Context 对象(例如dsClient.Get(ctx, k, e)),那么应该使用HTTP 请求的上下文吗?
我是 Go 新手,真的找不到任何在线资源可以通过真实世界的示例和实际的最佳实践模式很好地解释此类问题。
【问题讨论】:
标签: go google-cloud-platform google-cloud-datastore