golang goroutine 无法抛错就用 errgroup

一般在golang 中想要并发运行业务时会直接开goroutine,关键字go ,但是直接go的话函数是无法对返回数据进行处理error的。

解决方案:

  • 初级版本:

一般是直接在出错的地方打入log日志,将出的错误记录到日志文件中,也可以集合日志收集系统直接将该错误用邮箱或者办公软件发送给你如:钉钉机器人+graylog.

  • 中级版本

当然你也可以自己在log包里封装好可以接受channel。

利用channel通道,将go中出现的error传入到封装好的带有channel接受器的log包中,进行错误收集或者通知通道接受return出来即可

  • 终极版本 errgroup

这个包是google对go的一个扩展包:

golang.org/x/sync/errgroup

怎么调用

我们直接看看官方test的demo调用:


func ExampleGroup_justErrors() {
    var g errgroup.Group
    var urls = []string{
        "http://www.golang.org/",
        "http://www.google.com/",
        "http://www.somestupidname.com/",
    }
    for _, url := range urls {
        // Launch a goroutine to fetch the URL.
        url := url // https://golang.org/doc/faq#closures_and_goroutines
        g.Go(func() error {
            // Fetch the URL.
            resp, err := http.Get(url)
            if err == nil {
                resp.Body.Close()
            }
            return err
        })
    }
    // Wait for all HTTP fetches to complete.
    if err := g.Wait(); err == nil {
        fmt.Println("Successfully fetched all URLs.")
    }
}

很简单的一个并发爬虫网页请求,请求中只要有一个有错误就会返回error。

再来看一种代有上下文context的调用:

func TestWithContext(t *testing.T) {
    errDoom := errors.New("group_test: doomed")

    cases := []struct {
        errs []error
        want error
    }{
        {want: nil},
        {errs: []error{nil}, want: nil},
        {errs: []error{errDoom}, want: errDoom},
        {errs: []error{nil, errDoom}, want: errDoom},
    }

    for _, tc := range cases {
        g, ctx := errgroup.WithContext(context.Background())

        for _, err := range tc.errs {
            err := err
            g.Go(func() error {
                log.Error(err) // 当此时的err = nil 时,g.Go不会将 为nil 的 err 放入g.err中
                return err
            })
        }
        err := g.Wait() // 这里等待所有Go跑完即add==0时,此处的err是g.err的信息。
        log.Error(err)
        log.Error(tc.want)
        if err != tc.want {
            t.Errorf("after %T.Go(func() error { return err }) for err in %v\n"+
                "g.Wait() = %v; want %v",
                g, tc.errs, err, tc.want)
        }

        canceled := false
        select {
        case <-ctx.Done():
            // 由于上文中内部调用了cancel(),所以会有Done()接受到了消息
            // returns an error or ctx.Done is closed 
            // 在当前工作完成或者上下文被取消之后关闭
            canceled = true
        default:
        }
        if !canceled {
            t.Errorf("after %T.Go(func() error { return err }) for err in %v\n"+
                "ctx.Done() was not closed",
                g, tc.errs)
        }
    }
}


关于上下文的知识补充可以看链接:

上下文 Context

这里 调用了 errgroup.WithContext, 用于控制每一个goroutined的生理周期。
在不同的 Goroutine 之间同步请求特定的数据、取消信号以及处理请求的截止日期

总的来说api的使用还是很简单的,再来看看源码包吧

源码解析

// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package errgroup provides synchronization, error propagation, and Context
// cancelation for groups of goroutines working on subtasks of a common task.
package errgroup

import (
    "context"
    "sync"
)

// A Group is a collection of goroutines working on subtasks that are part of
// the same overall task.
//
// A zero Group is valid and does not cancel on error.
type Group struct {
    // cancel 初始化时会直接扔一个context.WithCancel(ctx)的cancel进入,然后通过它来进行removeChild removes a context from its parent
    // 这样真正调用其实是:func() { c.cancel(true, Canceled) }
    cancel func()
    
    // 包含了个 WaitGroup用于同步等待所有Gorourine执行
    
    wg sync.WaitGroup 

    // go语言中特有的单例模式,利用原子操作进行锁定值判断
    
    errOnce sync.Once
    
    err     error
}

// WithContext returns a new Group and an associated Context derived from ctx.
//
// The derived Context is canceled the first time a function passed to Go
// returns a non-nil error or the first time Wait returns, whichever occurs
// first.

func WithContext(ctx context.Context) (*Group, context.Context) {
    ctx, cancel := context.WithCancel(ctx)
    return &Group{cancel: cancel}, ctx
}

// Wait blocks until all function calls from the Go method have returned, then
// returns the first non-nil error (if any) from them.

func (g *Group) Wait() error {
    g.wg.Wait()
    if g.cancel != nil {
        g.cancel()
    }
    return g.err 
    // 这里返回的error其实是从众多goroutine中返回第一个非nil的错误信息,所以这个错误信息如果全部都是一样的话,你是不知道到底是哪个goroutine中报的错,应该在goroutine内部就写清楚错误信息的别分类似可以加入id值这种。
}

// Go calls the given function in a new goroutine.
//
// The first call to return a non-nil error cancels the group; its error will be
// returned by Wait.
func (g *Group) Go(f func() error) {
    g.wg.Add(1)

    go func() {
        defer g.wg.Done()

        if err := f(); err != nil {
            g.errOnce.Do(func() {
                g.err = err
                if g.cancel != nil {
                    // 如果出现第一个err为非nil就会去调用关闭接口,即关闭后面的所有子gorourine
                    g.cancel()
                }
            })
        }
    }()
}



开源引用demo

这里介绍一个 bilibili errgroup 包:

bilbil/kratos

另外 官方包golang.org/sync/errgroup 的 test 也可以看看。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 227,401评论 6 531
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,011评论 3 413
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 175,263评论 0 373
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 62,543评论 1 307
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,323评论 6 404
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,874评论 1 321
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,968评论 3 439
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,095评论 0 286
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,605评论 1 331
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,551评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,720评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,242评论 5 355
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,961评论 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,358评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,612评论 1 280
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,330评论 3 390
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,690评论 2 370

推荐阅读更多精彩内容