在“微服务”时代,我们在处理一个请求时经常调用多个外部微服务并综合处理返回结果:
func handleRequestClassic() {r1 := invokeService1()//handle result1r2 := invokeService2()//handle result2r3 := invokeService3()//handle result3}
上述例子中的问题是显而易见的:顺序调用、慢、一旦某个service出现异常,返回时间不可预知,可能会导致调用阻塞。
一个优化的方法就是讲将处理请求时对外部的服务调用分发到goroutine中,再汇总返回结果。并且通过设置一个总体超时时间,让调用返回的时间可预知。
func handleRequestByDAM() {c1, c2, c3 := make(chan Result1), make(chan Result2), make(chan Result3)go func() { c1 <- invokeService1() } ()go func() { c2 <- invokeService2() } ()go func() { c3 <- invokeService3() } ()timeout := time.After(200 * time.Millisecond)for i := 0; i < 3; i++ {select {case r := <-c1: //handle result1c1 = nilcase r := <-c2: //handle result2c2 = nilcase r := <-c3: //handle result3c3 = nilcase <-timeout:fmt.Println("timed out")return}}return}
不过这次优化后的程序依旧存在一个问题,那就是一旦timeout,调用返回,但一些在途的请求资源可能没有回收,request无法显式撤回,久而久之,可能导致资源的泄露。于是我们做进一步改进:通过Context显式cancel掉已经向外发起的在途请求,释放占用资源:
type service func() resultfunc invokeService(ctx context.Context, s service) chan result {c := make(chan result)go func() {c1 := make(chan result)go func() {c1 <-s()}select {case v := <-c1:c <-vcase <-ctx.Done():// cancel this in-flight request by closing its connection.}}()return c}func handleRequestByDAM() {ctx, cf := context.WithCancel(context.Background())c1, c2, c3 := invokeService(ctx, service1), invokeService(ctx, service2),invokeService(ctx, service3)timeout := time.After(200 * time.Millisecond)for i := 0; i < 3; i++ {select {case r := <-c1: //handle result1case r := <-c2: //handle result2case r := <-c3: //handle result3case <-timeout:cf() // cancel all service invoke requestsreturn}}return}
优化后的程序的优点:并发、快、返回结果可预知。
