我正在使用 Go BigQuery 客户端软件包,但我对 context
的用法有点困惑。
在文档中,只有 Put
函数明确提到使用带超时的新上下文以避免无限期重试。对所有其他调用使用 context.Background()
是否安全?
最佳答案
来自golang site :
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
上下文被设计为针对每个用例进行调整和定制。您可以使用库提供的功能来实现这一目标。
The WithCancel, WithDeadline, and WithTimeout functions take a Context (the parent) and return a derived Context (the child) and a CancelFunc. Calling the CancelFunc cancels the child and its children, removes the parent's reference to the child, and stops any associated timer
因此,goDocs建议在您的上下文中使用 WithTimeout 函数,同时将数据插入 BigQuery 并防止重复,正如您已经看到的那样。
唯一必须的是传递一个非零的上下文。您通常会使用 context.Background()
作为一种方法(正如我在从 Cloud Github 共享的 snippets.go 中看到的那样),但您可以安全地传递 context.TODO
如果您不确定使用哪一个。
关于go - BigQuery golang 客户端 : which context to use?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58663560/