Go Context 取消与超时实践WithTimeout 示例package main import ( "context" "net/http" "time" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil) _, _ = http.DefaultClient.Do(req) } 取消链路func worker(ctx context.Context) error { select { case <-time.After(500*time.Millisecond): return nil case <-ctx.Done(): return ctx.Err() } } 规范为外层创建的上下文负责取消在阻塞点监听 `ctx.Done()` 并返回 `ctx.Err()`总结通过超时与取消信号传递,可提高服务的弹性与资源回收效率。

发表评论 取消回复