猿问

go中使用channel实现重试机制

我正在启动两个并发执行路径(又名 goroutines)来执行两个作业



    const Retries = 10


    wg.Add(2)

    go func() {

        for i := 0; i < Retries; i++ {

            retVal1, err1 = doSomeWork()

            if err1 != nil {

                fmt.Printf("WARNING: Error job in attempt no %d: %s - retrying...\n", i+1, err1)

                continue

            } else {

                break

            }

        }

        if err1 != nil {

            log.Fatalf("ERROR job %s\n", err1)

        }

        wg.Done()

    }()

    go func() {

        for i := 0; i < Retries; i++ {

            retVal2, err2 = doSomeWork()

            if err2 != nil {

                fmt.Printf("WARNING: Error job in attempt no %d: %s - retrying...\n", i+1, err2)

                continue

            } else {

                break

            }

        }

        if err2 != nil {

            log.Fatalf("ERROR job %s\n", err2)

        }

        wg.Done()

    }()

    wg.Wait()

我的问题是(除了导入一些第三方重试库)是否有更多惯用的方式来构建上述代码?渠道/选择方法会更加以去为中心吗?


MYYA
浏览 165回答 1
1回答

人到中年有点甜

你的代码还不错。使用频道将是一个矫枉过正。我会这样写,稍微轻一点。const maxRetries int = 3go func() {&nbsp; &nbsp; var retries int&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; retVal1, err1 = doSomeWork()&nbsp; &nbsp; &nbsp; &nbsp; if err1 == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; retries++&nbsp; &nbsp; &nbsp; &nbsp; if retries == maxRetries {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatalf("ERROR job %s\n", err1)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("WARNING: Error job in attempt no %d: %s - retrying...\n", retries, err1)&nbsp; &nbsp; }&nbsp; &nbsp; wg.Done()}()
随时随地看视频慕课网APP

相关分类

Go
我要回答