在“微服务”时代,我们在处理一个请求时经常调用多个外部微服务并综合处理返回结果:

    1. func handleRequestClassic() {
    2. r1 := invokeService1()
    3. //handle result1
    4. r2 := invokeService2()
    5. //handle result2
    6. r3 := invokeService3()
    7. //handle result3
    8. }

    上述例子中的问题是显而易见的:顺序调用、慢、一旦某个service出现异常,返回时间不可预知,可能会导致调用阻塞。
    一个优化的方法就是讲将处理请求时对外部的服务调用分发到goroutine中,再汇总返回结果。并且通过设置一个总体超时时间,让调用返回的时间可预知。

    1. func handleRequestByDAM() {
    2. c1, c2, c3 := make(chan Result1), make(chan Result2), make(chan Result3)
    3. go func() { c1 <- invokeService1() } ()
    4. go func() { c2 <- invokeService2() } ()
    5. go func() { c3 <- invokeService3() } ()
    6. timeout := time.After(200 * time.Millisecond)
    7. for i := 0; i < 3; i++ {
    8. select {
    9. case r := <-c1: //handle result1
    10. c1 = nil
    11. case r := <-c2: //handle result2
    12. c2 = nil
    13. case r := <-c3: //handle result3
    14. c3 = nil
    15. case <-timeout:
    16. fmt.Println("timed out")
    17. return
    18. }
    19. }
    20. return
    21. }

    不过这次优化后的程序依旧存在一个问题,那就是一旦timeout,调用返回,但一些在途的请求资源可能没有回收,request无法显式撤回,久而久之,可能导致资源的泄露。于是我们做进一步改进:通过Context显式cancel掉已经向外发起的在途请求,释放占用资源:

    1. type service func() result
    2. func invokeService(ctx context.Context, s service) chan result {
    3. c := make(chan result)
    4. go func() {
    5. c1 := make(chan result)
    6. go func() {
    7. c1 <-s()
    8. }
    9. select {
    10. case v := <-c1:
    11. c <-v
    12. case <-ctx.Done():
    13. // cancel this in-flight request by closing its connection.
    14. }
    15. }()
    16. return c
    17. }
    18. func handleRequestByDAM() {
    19. ctx, cf := context.WithCancel(context.Background())
    20. c1, c2, c3 := invokeService(ctx, service1), invokeService(ctx, service2),
    21. invokeService(ctx, service3)
    22. timeout := time.After(200 * time.Millisecond)
    23. for i := 0; i < 3; i++ {
    24. select {
    25. case r := <-c1: //handle result1
    26. case r := <-c2: //handle result2
    27. case r := <-c3: //handle result3
    28. case <-timeout:
    29. cf() // cancel all service invoke requests
    30. return
    31. }
    32. }
    33. return
    34. }

    优化后的程序的优点:并发、快、返回结果可预知。