dpyoh6553
2018-01-01 10:32
浏览 69
已采纳

如何在Golang Google数据存储包中正确使用上下文?

I've started using Google Cloud Datastore in one of the project in the company I currently work in.

https://godoc.org/cloud.google.com/go/datastore

In the provided example, they use a context and pass it to the connection instance

ctx := context.Background()
dsClient, err := datastore.NewClient(ctx, "my-project")

Through the documentation you will see that they pass a context to all the functions that makes operations on the database, I am not sure if they are passing the same pointer or create a new pointer for each operation.

The current setup that I have is a global variable for the context in a package called "store" which I keep all the structs functions that communicate with the db, and I use that global variable each time. I don't know what is the effect of that, I am not sure why the context is used, Should I get reference of context.Background() each time I make operations on the database ?

图片转代码服务由CSDN问答提供 功能建议

我已经在我目前工作的公司的一个项目中开始使用Google Cloud Datastore。

https://godoc.org/cloud.google。 com / go / datastore

在提供的示例中,他们使用上下文并将其传递给连接实例

   ctx:= context.Background()
dsClient,err:= datastore.NewClient(ctx,“ my-project”)
   
 
 

通过文档,您将看到 它们将上下文传递给在数据库上进行操作的所有函数,我不确定它们是否传递相同的指针或为每个操作创建新的指针。

当前的设置 我在名为“ store”的程序包中有一个用于上下文的全局变量,它保留与数据库通信的所有结构函数,并且每次都使用该全局变量。 我不知道这样做有什么作用,我不确定为什么要使用上下文,每次我对数据库进行操作时,是否应该获得 context.Background()的引用?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doucan957495 2018-01-02 06:53
    已采纳

    context.Background is the global context--so no need for you global variable. Most of the time you'll want to use a child of that context, with a cancel or a timeout.

    ctx, cancel := context.WithCancel(context.Background)
    //or
    ctx, cancel := context.WithTimeout(context.Background, time.Second * 30) 
    

    Then you can use the cancel function to close down your application nicely, or cancel and retry if a request is hanging. If you never plan on canceling or timing out operations, then using context.Background is fine.

    Also context.Context is an interface so it's always passed by reference, so all uses of a certain instance point to the same context.

    打赏 评论

相关推荐 更多相似问题