Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在重用mongodb连接时处理上下文_Mongodb_Go - Fatal编程技术网

在重用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()

}