GoLang教程——Context上下文实战

大家好,我是极客老墨。 写并发程序时,经常遇到这样的场景:用户关闭了浏览器,但后台的数据库查询还在跑;API 调用超时了,但 Goroutine 还在等待响应。这些"失控"的 Goroutine 会浪费资源,甚至导致内存泄漏。 Go 的 Context 就是用来解决这个问题的。它能控制 Goroutine 的生命周期,实现超时、取消和数据传递。 这篇就聊聊 Context 的核心用法,看看它是怎么管理并发任务的。 Context 是什么 Context 是一个接口,定义了四个方法: 1type Context interface { 2 Deadline() (deadline time.Time, ok bool) 3 Done() <-chan struct{} 4 Err() error 5 Value(key interface{}) interface{} 6} 核心功能: 取消信号:通知 Goroutine 停止工作 超时控制:限制任务执行时间 数据传递:在调用链中传递元数据 创建 Context Go 提供了几个函数来创建 Context。 Background 和 TODO 1import "context" 2 3// Background:根 Context,通常在 main 函数中使用 4ctx := context.Background() 5 6// TODO:当不确定用什么 Context 时使用 7ctx := context.TODO() 要点: Background 是最顶层的 Context TODO 用于占位,表示还没想好用什么 两者都不会被取消,没有超时,没有值 WithCancel:手动取消 1// 创建可取消的 Context 2ctx, cancel := context.WithCancel(context.Background()) 3 4// 调用 cancel 取消 Context 5cancel() WithTimeout:超时自动取消 1// 2 秒后自动取消 2ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) 3defer cancel() WithDeadline:指定截止时间 1// 指定截止时间 2deadline := time.Now().Add(2 * time.Second) 3ctx, cancel := context.WithDeadline(context.Background(), deadline) 4defer cancel() WithValue:传递数据 1// 存储键值对 2ctx := context.WithValue(context.Background(), "userID", 123) 3 4// 获取值 5if userID, ok := ctx.Value("userID").(int); ok { 6 fmt.Println("User ID:", userID) 7} 超时控制 超时控制是 Context 最常用的场景。 ...

2025-03-02 · 7 min · 1481 words · 老墨