rpc调用是在实际开发场景中经常用到的,假设某个用户请求的处理需要3个RPC并行请求,设置一个整体任务的超时时间,如果到达超时时间后,不管RPC有没有执行完毕任务都返回,实现逻辑见下面代码:

package main

import (
	"context"
	"fmt"
	"strconv"
	"sync"
	"time"
)

//rpc调用
func Rpc(ctx context.Context, url string) string {
	result := make(chan string)
	//开启一个新的协程去执行rpc调用逻辑
	go func() {
		//...balabala
		if url == "http://rpc_2_url" { //假设rpc-2服务比较耗时 就假设要2s吧
			time.Sleep(2*time.Second)
		}
		rpcResult := url+"xxxx" //假设调用rpc得到的数据就是这个样子
		result<-rpcResult
	}()
	//当前协程监听通道事件(整体任务的超时时间到/当前rpc调用完成了)
	select {
	case <- ctx.Done(): //context的超时事件
		// 如果规定的时间到了,没有得到结果也立即返回
		return ""
	case r:=<- result: //本RPC调用成功,返回结果
		return r
	}
}


func main() {
	//设置整个任务超时时间为1s
	ctx, _ := context.WithTimeout(context.Background(),1*time.Second)
	wg := sync.WaitGroup{}
	var lastRes string

	rcpUrl:=