背景
有这么个需求
1、调用多个服务,pack1、pack2、pack3…,需要并行调用;
2、任意一个服务返回失败,提前返回失败
3、需要有超时控制不能等待太久
4、收集每个服务返回的结果,后面要做处理
怎么实现呢?
code
package main
import (
"code.byted.org/gopkg/logs"
"fmt"
"github.com/pkg/errors"
"time"
)
func pack1(secs time.Duration) (result string, err error) {
fmt.Printf("waiting %v\n", secs)
time.Sleep(secs * time.Second)
result = fmt.Sprintf("waited for %v seconds", secs)
//return result, errors.New("pack1 error")
return result, nil
}
func pack2(secs time.Duration) (result string, err error) {
fmt.Printf("waiting %v\n", secs)
time.Sleep(secs * time.Second)
result = fmt.Sprintf("waited for %v seconds", secs)
return result, errors.New("pack2 error")
//return result, nil
}
// golang parallel return functions
// 并行执行多个pack,只要有一个错误,就可以提前返回,否则需要收集多个pack结果拼接一起(reduce)
func runParallel() (string, error) {
defer logs.Flush()
outChan1 := make(chan *string)
outChan2 := make(chan *string)
go func() {
res1, err := pack1(1)
if err != nil {
logs.Error("pack1 error")
outChan1