亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

重用 mongodb 連接時處理上下文

重用 mongodb 連接時處理上下文

Go
慕斯709654 2022-08-15 15:47:51
我通過作為參數傳遞來使多個 goroutine 共享單個連接。clienturi := "mongodb://localhost:27017"ctx := context.Background()client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))go Foo(client)go Bar(client)func Foo(client *mongo.Client) {        // ... }func Bar(client *mongoClient) {        // ...}我對如何處理感到困惑。我應該在每次查詢數據庫時都創建一個新上下文,還是應該像客戶端一樣重用上下文?ctx
查看完整描述

2 回答

?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

這取決于您的和方法的行為方式。讓我們想象一下,該方法是一個簡單的短命goroutine,它對DB進行一個查詢,您唯一想要的就是檢查其父上下文是否為“完成”或“取消”。然后,您可以為 Foo 方法提供父上下文。FooBarFoo


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...")

    }

}

另一方面,如果執行一些重要的邏輯并對 DB 進行多次調用,您可能希望一個單獨的上下文能夠將其與父上下文分開取消。然后,您可以從父母那里獲得新的上下文。Bar


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()


}


查看完整回答
反對 回復 2022-08-15
?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

我也這樣做過


type DB struct {

    client *mongo.Client

}


func (db *DB) GetVideoStream {}


func main() {

    ctx, _ := context.WithTimeout(context.Background(), 60*time.Second)

    client, err := mongo.Connect(ctx, clientOpts)

    db := &DB{client: client}

    go db.GetVideoStream()

    http.HandleFunc("/api/", db.GetVideoStream)

}

您可以使用指針接收器來執行相同的操作。


我是新來的,還是該語言的新手


查看完整回答
反對 回復 2022-08-15
  • 2 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號