• 郑海成
    2025-07-11 来自北京
    package main import ( "context" "fmt" "math/rand" "sync" "time" ) type RPCService struct { Name string } func (s *RPCService) Call(ctx context.Context) error { sleepTime := time.Duration(100+rand.Intn(400)) * time.Millisecond select { case <-time.After(sleepTime): if rand.Intn(3) == 0 { return fmt.Errorf("call RPC %s failed", s.Name) } fmt.Printf("call RPC %s success with TraceID: %s\n", s.Name, ctx.Value("TraceId")) case <-ctx.Done(): fmt.Printf("call RPC %s canceled\n", s.Name) return fmt.Errorf("call RPC %s canceled", s.Name) } return nil } func main() { // 派生一个有500ms超时时间的上下文 ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) // 派生一个传递 TraceId 的上下文 ctx = context.WithValue(ctx, "TraceId", "123456") // 创建ABC三个RPC调用 clients := []*RPCService{ {Name: "RPC-A"}, {Name: "RPC-B"}, {Name: "RPC-C"}, } wg := sync.WaitGroup{} // 在子协程中调用 RPC for _, client := range clients { wg.Add(1) go func(client *RPCService) { defer wg.Done() // 调用 RPC err := client.Call(ctx) if err != nil { cancel() // 调用失败,取消上下文 } }(client) } wg.Wait() // 等待所有子协程结束 }
    展开

    作者回复: ✅

    
    