Golang context用于跨goroutine传递取消信号、截止时间和请求数据,通过context.Background或WithCancel/Deadline/Timeout/Value创建并传递,各goroutine监听Done()通道实现协同取消,Value可传递请求级数据如请求ID,但应避免滥用以确保可维护性。
Golang context 旨在简化对跨 API 边界和 goroutine 之间请求范围值的处理,特别是用于取消操作、设置截止时间和传递请求相关值。它并非直接控制协程,而是提供一种优雅的方式来传递信号和数据,进而影响协程的行为。
Context 通过
context.Context
创建 Context:
context.Background()
context.TODO()
context.Background()
context.WithCancel(parent)
context.WithDeadline(parent, time)
context.WithTimeout(parent, duration)
context.WithValue(parent, key, value)
传递 Context:
立即学习“go语言免费学习笔记(深入)”;
将 Context 作为函数的第一个参数传递。这是一种约定,可以确保 Context 在整个调用链中可用。
func processRequest(ctx context.Context, req *Request) error { // ... }
使用 Context:
检查取消信号: 使用
ctx.Done()
select
func worker(ctx context.Context) { for { select { case <-ctx.Done(): fmt.Println("Worker: context cancelled") return default: // 执行工作 fmt.Println("Worker: doing some work") time.Sleep(time.Second) } } }
检查截止时间: 使用
ctx.Err()
ctx.Err()
errors.Is(ctx.Err(), context.Canceled)
errors.Is(ctx.Err(), context.DeadlineExceeded)
func doSomething(ctx context.Context) error { select { case <-time.After(time.Duration(10) * time.Second): // Operation completed successfully return nil case <-ctx.Done(): return ctx.Err() // Returns context.Canceled or context.DeadlineExceeded } }
获取键值对: 使用
ctx.Value(key)
userID := ctx.Value("user_id").(string)
取消 Context:
context.WithCancel
context.WithDeadline
context.WithTimeout
Context 的取消功能是其核心优势之一,尤其在涉及多个并发 Goroutine 时。想象一个场景:你发起一个需要多个 Goroutine 协同完成的任务,但如果其中一个 Goroutine 失败了,你希望立即停止所有 Goroutine 的工作。Context 就可以派上用场。
首先,使用
context.WithCancel
Done()
func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() // 确保在 main 函数退出时取消 Context // 启动多个 Goroutine,并将 Context 传递给它们 for i := 0; i < 5; i++ { go worker(ctx, i) } // 模拟一个 Goroutine 失败的情况 time.Sleep(3 * time.Second) fmt.Println("Main: cancelling context") cancel() // 取消 Context,通知所有 Goroutine 停止工作 time.Sleep(time.Second) // 等待 Goroutine 退出 fmt.Println("Main: done") } func worker(ctx context.Context, id int) { for { select { case <-ctx.Done(): fmt.Printf("Worker %d: context cancelled\n", id) return default: fmt.Printf("Worker %d: doing some work\n", id) time.Sleep(time.Second) } } }
在这个例子中,
main
worker
main
cancel()
worker
Context 除了取消和超时控制外,还能携带键值对。这看似简单的功能,在某些场景下却能发挥巨大的作用。例如,你可以在 Context 中存储请求 ID、用户身份验证信息、跟踪 ID 等。这些信息可以在整个请求处理过程中访问,无需显式地在函数之间传递。
一个常见的应用场景是在 HTTP 中间件中设置请求 ID,然后在后续的处理函数中使用该 ID 进行日志记录或跟踪。
func requestIDMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requestID := uuid.New().String() ctx := context.WithValue(r.Context(), "request_id", requestID) next.ServeHTTP(w, r.WithContext(ctx)) }) } func myHandler(w http.ResponseWriter, r *http.Request) { requestID := r.Context().Value("request_id").(string) log.Printf("Request ID: %s\n", requestID) // ... }
需要注意的是,Context 的 Value 应该只用于传递请求范围的数据,而不是用于传递可选参数或配置信息。对于可选参数或配置信息,应该使用函数参数或全局变量。此外,Context 的 Value 应该是不可变的,以避免并发问题。
Context 虽好,但使用不当也可能导致问题。一个常见的问题是过度使用 Context 的 Value。如果每个函数都从 Context 中获取大量数据,代码的可读性和可维护性将大大降低。
另一个问题是忘记取消 Context。如果一个 Goroutine 启动后没有正确地监听 Context 的
Done()
为了避免这些问题,应该遵循以下最佳实践:
Done()
contextcheck
此外,要注意Context传递的开销。虽然Context本身开销不大,但如果频繁创建和传递包含大量Value的Context,也会对性能产生一定影响。 在性能敏感的场景下,需要仔细评估Context的使用方式。
以上就是Golang context如何使用 实现协程控制与超时的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号