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

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

同時等待兩個結果并超時

同時等待兩個結果并超時

Go
小怪獸愛吃肉 2023-07-10 16:30:35
使用案例我想對數據庫并行運行兩個查詢,并在最多 600 毫秒后返回我當時獲取的任何內容。我正在努力實現此要求的并發性。代碼func (s *Service) GetCustomerStats(ctx context.Context, customerUUID string) *CustomerStats {    stats := &CustomerStats{        CustomerUUID: customerUUID,        Type:         "ERROR",        OrderCount:   "ERROR",    }    var wg sync.WaitGroup    var mu sync.Mutex    // Get order count    wg.Add(1)    go func() {        defer wg.Done()        orderCount, err := s.Storage.GetOrderCount(ctx, customerUUID)        if err != nil {            return        }        mu.Lock()        stats.OrderCount = strconv.Itoa(orderCount)        if orderCount == 0 {            stats.OrderCount = "NA"        }        mu.Unlock()    }()    // Get customer type    wg.Add(1)    go func() {        defer wg.Done()        type, err := s.Storage.GetCustomerType(ctx, customerUUID)        if err != nil {            return        }        mu.Lock()        stats.Type = strconv.Itoa(type)        mu.Unlock()    }()    wg.Wait()    return stats}問題我傳遞給該函數的上下文定義了 600 毫秒的超時。我將它傳遞給存儲存儲庫,數據庫驅動程序也使用它,但它不能保證它會在這段時間內做出響應,因為它確實會在后臺安排一些重試。但是我必須確保該函數在傳遞的上下文超時(600 毫秒)內返回。我目前正在使用等待組來等待結果,但我不知道stats上下文完成后如何返回?;旧衔艺趯ふ疫@樣的東西。我的研究表明,我可能應該使用表明工作已完成的通道,但我不確定如何實現它,以便它是簡單的代碼。    select {    case wg.Wait()        return stats    case <-ctx.Done()        return stats    }
查看完整描述

1 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

您計劃選擇的方式看起來ctx.Done()是正確的。

在我看來,你處理可變狀態的方式是錯誤的。


嘗試這樣的事情:


 var state = State{}

 select {

    case type <- typeChan

        stats.Type = type

        if (stats.OrderCount != nil) {

           return stats

        }

    case count <- countChan

        stats.OrderCount = count

        if (stats.Type != nil) {

           return stats

        }

    case <-ctx.Done()

        return stats

    }

現在你的函數應該是這樣的:


go func() {        

    orderCount, err := s.Storage.GetOrderCount(ctx, customerUUID)

    if err != nil {

        return // Here you probably want to have errChan

    }


    if orderCount == 0 {

        countChan <- "NA"

    } else {

        countChan <- strconv.Itoa(orderCount)

    }        

}()

這一切都有點粗略,因為您的示例非常復雜,但應該為您提供遵循的方向。


查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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