在重用mongodb连接时处理上下文
我通过将在重用mongodb连接时处理上下文,mongodb,go,Mongodb,Go,我通过将client作为参数传递,使多个goroutine共享一个连接 uri:=”mongodb://localhost:27017" ctx:=context.Background() client,err:=mongo.Connect(ctx,options.client().ApplyURI(uri)) go Foo(客户) go Bar(客户) func Foo(客户端*mongo.client){ // ... } 功能条(客户端*mongoClient){ // ... } 我
client
作为参数传递,使多个goroutine共享一个连接
uri:=”mongodb://localhost:27017"
ctx:=context.Background()
client,err:=mongo.Connect(ctx,options.client().ApplyURI(uri))
go Foo(客户)
go Bar(客户)
func Foo(客户端*mongo.client){
// ...
}
功能条(客户端*mongoClient){
// ...
}
我不知道如何使用
ctx
。我应该在每次查询数据库时创建一个新的上下文,还是像客户端一样重用上下文?这取决于Foo
和Bar
方法的行为。让我们想象一下Foo
方法是一个简单的短期goroutine,它对DB进行一次查询,您只需要检查其父上下文是否未完成或取消。然后可以为Foo方法提供父上下文
func main() {
uri := "mongodb://localhost:27017"
ctx := context.Background()
client, err := Connect(ctx, uri)
ctx, cancel := context.WithCancel(ctx)
if err != nil {
panic(err)
}
go Foo(ctx, client)
go Bar(context.WithValue(ctx, "uri", uri), client)
// cancel parent context
cancel()
time.Sleep(5*time.Second)
}
func Foo(ctx context.Context, client *Client) {
fmt.Printf("Foo: %s\n", ctx.Value("uri"))
select {
case <- ctx.Done():
err := ctx.Err()
if err != nil {
// you could switch for the actual reason
fmt.Println("In our case context canceled: ", err)
return
}
fmt.Printf("Do something...")
}
}
func Bar(ctx context.Context, client *Client) {
// Bar has a non trivial logic and needs a separate cancellation and handling
ctx, cancelFunc := context.WithCancel(ctx)
fmt.Printf("Bar: %s\n", ctx.Value("uri"))
// cancel derived context
cancelFunc()
}