Go学习笔记-Context

Context包提供了在goroutine之间传递取消信号、超时和其他请求范围值的标准方式。它是Go语言中处理超时、取消和传递请求数据的核心机制。

Context基础

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main

import (
    "context"
    "fmt"
    "time"
)

// 1. 基本Context使用
func basicContextExample() {
    fmt.Println("=== 基本Context使用 ===")
    
    // 创建根context
    ctx := context.Background()
    fmt.Printf("根context: %v\n", ctx)
    
    // 创建TODO context(当不确定使用哪个context时)
    todoCtx := context.TODO()
    fmt.Printf("TODO context: %v\n", todoCtx)
    
    // 创建带取消功能的context
    cancelCtx, cancel := context.WithCancel(ctx)
    defer cancel() // 确保释放资源
    
    fmt.Printf("可取消context: %v\n", cancelCtx)
    
    // 检查context是否被取消
    select {
    case <-cancelCtx.Done():
        fmt.Println("Context已被取消")
    default:
        fmt.Println("Context未被取消")
    }
    
    // 取消context
    cancel()
    
    // 再次检查
    select {
    case <-cancelCtx.Done():
        fmt.Printf("Context已被取消,原因: %v\n", cancelCtx.Err())
    default:
        fmt.Println("Context未被取消")
    }
}

// 2. 超时Context
func timeoutContextExample() {
    fmt.Println("\n=== 超时Context ===")
    
    // 创建5秒超时的context
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    
    // 模拟长时间运行的操作
    longRunningTask := func(ctx context.Context, name string, duration time.Duration) {
        fmt.Printf("%s 开始执行,预计耗时: %v\n", name, duration)
        
        select {
        case <-time.After(duration):
            fmt.Printf("%s 正常完成\n", name)
        case <-ctx.Done():
            fmt.Printf("%s 被取消: %v\n", name, ctx.Err())
        }
    }
    
    // 启动多个任务
    go longRunningTask(ctx, "任务1", 2*time.Second)  // 会正常完成
    go longRunningTask(ctx, "任务2", 7*time.Second)  // 会超时
    go longRunningTask(ctx, "任务3", 3*time.Second)  // 会正常完成
    
    // 等待context超时或所有任务完成
    <-ctx.Done()
    fmt.Printf("主程序结束,原因: %v\n", ctx.Err())
    
    // 给一点时间让输出完成
    time.Sleep(100 * time.Millisecond)
}

// 3. 截止时间Context
func deadlineContextExample() {
    fmt.Println("\n=== 截止时间Context ===")
    
    // 设置截止时间为3秒后
    deadline := time.Now().Add(3 * time.Second)
    ctx, cancel := context.WithDeadline(context.Background(), deadline)
    defer cancel()
    
    fmt.Printf("截止时间: %v\n", deadline.Format("15:04:05"))
    
    // 检查剩余时间
    if deadline, ok := ctx.Deadline(); ok {
        remaining := time.Until(deadline)
        fmt.Printf("剩余时间: %v\n", remaining)
    }
    
    // 模拟工作
    for i := 1; i <= 5; i++ {
        select {
        case <-ctx.Done():
            fmt.Printf("在第%d次迭代时被取消: %v\n", i, ctx.Err())
            return
        default:
            fmt.Printf("执行第%d次迭代\n", i)
            time.Sleep(1 * time.Second)
        }
    }
    
    fmt.Println("所有迭代完成")
}

func main() {
    basicContextExample()
    timeoutContextExample()
    deadlineContextExample()
}

Context传值

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package main

import (
    "context"
    "fmt"
)

// 1. 定义context key类型
type contextKey string

const (
    UserIDKey    contextKey = "userID"
    RequestIDKey contextKey = "requestID"
    TraceIDKey   contextKey = "traceID"
)

// 2. 用户信息结构
type User struct {
    ID   int
    Name string
    Role string
}

// 3. 请求信息结构
type RequestInfo struct {
    ID        string
    Method    string
    Path      string
    UserAgent string
}

// 4. 从context中获取用户信息
func GetUserFromContext(ctx context.Context) (*User, bool) {
    user, ok := ctx.Value(UserIDKey).(*User)
    return user, ok
}

// 5. 从context中获取请求ID
func GetRequestIDFromContext(ctx context.Context) (string, bool) {
    requestID, ok := ctx.Value(RequestIDKey).(string)
    return requestID, ok
}

// 6. 模拟中间件:添加请求信息到context
func withRequestInfo(ctx context.Context, method, path, userAgent string) context.Context {
    requestInfo := &RequestInfo{
        ID:        fmt.Sprintf("req-%d", time.Now().UnixNano()),
        Method:    method,
        Path:      path,
        UserAgent: userAgent,
    }
    
    ctx = context.WithValue(ctx, RequestIDKey, requestInfo.ID)
    return ctx
}

// 7. 模拟中间件:添加用户信息到context
func withUser(ctx context.Context, user *User) context.Context {
    return context.WithValue(ctx, UserIDKey, user)
}

// 8. 模拟服务层函数
func getUserProfile(ctx context.Context) error {
    // 获取请求ID用于日志
    requestID, _ := GetRequestIDFromContext(ctx)
    fmt.Printf("[%s] 获取用户资料\n", requestID)
    
    // 获取当前用户
    user, ok := GetUserFromContext(ctx)
    if !ok {
        return fmt.Errorf("未找到用户信息")
    }
    
    fmt.Printf("[%s] 用户: %s (ID: %d, 角色: %s)\n", 
        requestID, user.Name, user.ID, user.Role)
    
    return nil
}

// 9. 模拟数据库操作
func queryDatabase(ctx context.Context, query string) error {
    requestID, _ := GetRequestIDFromContext(ctx)
    user, _ := GetUserFromContext(ctx)
    
    fmt.Printf("[%s] 执行数据库查询: %s\n", requestID, query)
    fmt.Printf("[%s] 查询用户: %s\n", requestID, user.Name)
    
    // 模拟数据库操作时间
    select {
    case <-time.After(100 * time.Millisecond):
        fmt.Printf("[%s] 数据库查询完成\n", requestID)
        return nil
    case <-ctx.Done():
        fmt.Printf("[%s] 数据库查询被取消: %v\n", requestID, ctx.Err())
        return ctx.Err()
    }
}

// 10. 链式context传递示例
func contextChainExample() {
    fmt.Println("=== Context链式传递 ===")
    
    // 创建根context
    ctx := context.Background()
    
    // 添加超时
    ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
    defer cancel()
    
    // 添加请求信息
    ctx = withRequestInfo(ctx, "GET", "/api/user/profile", "Mozilla/5.0")
    
    // 添加用户信息
    user := &User{
        ID:   123,
        Name: "张三",
        Role: "admin",
    }
    ctx = withUser(ctx, user)
    
    // 调用服务
    if err := getUserProfile(ctx); err != nil {
        fmt.Printf("获取用户资料失败: %v\n", err)
        return
    }
    
    // 调用数据库
    if err := queryDatabase(ctx, "SELECT * FROM users WHERE id = ?"); err != nil {
        fmt.Printf("数据库查询失败: %v\n", err)
        return
    }
}

// 11. Context值的最佳实践
func contextValueBestPractices() {
    fmt.Println("\n=== Context值的最佳实践 ===")
    
    // 1. 使用自定义类型作为key,避免冲突
    type myKey int
    const (
        key1 myKey = iota
        key2
    )
    
    ctx := context.Background()
    ctx = context.WithValue(ctx, key1, "value1")
    ctx = context.WithValue(ctx, key2, "value2")
    
    // 2. 提供类型安全的访问函数
    getValue1 := func(ctx context.Context) (string, bool) {
        v, ok := ctx.Value(key1).(string)
        return v, ok
    }
    
    getValue2 := func(ctx context.Context) (string, bool) {
        v, ok := ctx.Value(key2).(string)
        return v, ok
    }
    
    if v1, ok := getValue1(ctx); ok {
        fmt.Printf("Key1的值: %s\n", v1)
    }
    
    if v2, ok := getValue2(ctx); ok {
        fmt.Printf("Key2的值: %s\n", v2)
    }
    
    // 3. 避免在context中存储可选参数
    // 好的做法:只存储请求范围的数据
    // 坏的做法:存储函数参数或配置信息
    
    fmt.Println("Context值应该用于请求范围的数据,如用户ID、请求ID、认证信息等")
    fmt.Println("不应该用于传递可选参数或配置信息")
}

func main() {
    contextChainExample()
    contextValueBestPractices()
}

Context的高级用法

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

// 1. 可取消的工作池
type CancellableWorkerPool struct {
    workers int
    jobs    chan func(context.Context) error
    results chan error
    ctx     context.Context
    cancel  context.CancelFunc
    wg      sync.WaitGroup
}

func NewCancellableWorkerPool(workers int) *CancellableWorkerPool {
    ctx, cancel := context.WithCancel(context.Background())
    
    return &CancellableWorkerPool{
        workers: workers,
        jobs:    make(chan func(context.Context) error, 100),
        results: make(chan error, 100),
        ctx:     ctx,
        cancel:  cancel,
    }
}

func (p *CancellableWorkerPool) Start() {
    for i := 0; i < p.workers; i++ {
        p.wg.Add(1)
        go p.worker(i)
    }
}

func (p *CancellableWorkerPool) worker(id int) {
    defer p.wg.Done()
    
    for {
        select {
        case job, ok := <-p.jobs:
            if !ok {
                fmt.Printf("Worker %d 退出\n", id)
                return
            }
            
            fmt.Printf("Worker %d 开始执行任务\n", id)
            err := job(p.ctx)
            
            select {
            case p.results <- err:
            case <-p.ctx.Done():
                fmt.Printf("Worker %d 被取消\n", id)
                return
            }
            
        case <-p.ctx.Done():
            fmt.Printf("Worker %d 被取消\n", id)
            return
        }
    }
}

func (p *CancellableWorkerPool) Submit(job func(context.Context) error) {
    select {
    case p.jobs <- job:
    case <-p.ctx.Done():
        fmt.Println("工作池已关闭,无法提交任务")
    }
}

func (p *CancellableWorkerPool) Cancel() {
    p.cancel()
}

func (p *CancellableWorkerPool) Close() {
    close(p.jobs)
    p.wg.Wait()
    close(p.results)
}

func (p *CancellableWorkerPool) Results() <-chan error {
    return p.results
}

// 2. HTTP客户端超时示例
func httpClientWithTimeout() {
    fmt.Println("=== HTTP客户端超时示例 ===")
    
    // 模拟HTTP请求函数
    makeRequest := func(ctx context.Context, url string) error {
        fmt.Printf("开始请求: %s\n", url)
        
        // 模拟网络延迟
        delay := 2 * time.Second
        if url == "slow-api" {
            delay = 5 * time.Second
        }
        
        select {
        case <-time.After(delay):
            fmt.Printf("请求完成: %s\n", url)
            return nil
        case <-ctx.Done():
            fmt.Printf("请求被取消: %s, 原因: %v\n", url, ctx.Err())
            return ctx.Err()
        }
    }
    
    // 创建带超时的context
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    
    // 并发发起多个请求
    urls := []string{"fast-api", "slow-api", "medium-api"}
    var wg sync.WaitGroup
    
    for _, url := range urls {
        wg.Add(1)
        go func(u string) {
            defer wg.Done()
            makeRequest(ctx, u)
        }(url)
    }
    
    wg.Wait()
}

// 3. 数据库事务超时
func databaseTransactionTimeout() {
    fmt.Println("\n=== 数据库事务超时 ===")
    
    // 模拟数据库操作
    executeQuery := func(ctx context.Context, query string, duration time.Duration) error {
        fmt.Printf("执行查询: %s\n", query)
        
        select {
        case <-time.After(duration):
            fmt.Printf("查询完成: %s\n", query)
            return nil
        case <-ctx.Done():
            fmt.Printf("查询被取消: %s, 原因: %v\n", query, ctx.Err())
            return ctx.Err()
        }
    }
    
    // 模拟事务
    runTransaction := func(ctx context.Context) error {
        fmt.Println("开始事务")
        
        // 执行多个查询
        queries := []struct {
            sql      string
            duration time.Duration
        }{
            {"SELECT * FROM users", 500 * time.Millisecond},
            {"UPDATE users SET last_login = NOW()", 1 * time.Second},
            {"INSERT INTO audit_log VALUES (...)", 2 * time.Second},
        }
        
        for _, q := range queries {
            if err := executeQuery(ctx, q.sql, q.duration); err != nil {
                fmt.Println("事务回滚")
                return err
            }
        }
        
        fmt.Println("事务提交")
        return nil
    }
    
    // 设置事务超时
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    
    if err := runTransaction(ctx); err != nil {
        fmt.Printf("事务失败: %v\n", err)
    }
}

// 4. 级联取消示例
func cascadingCancellation() {
    fmt.Println("\n=== 级联取消示例 ===")
    
    // 父context
    parentCtx, parentCancel := context.WithCancel(context.Background())
    
    // 子context1
    childCtx1, childCancel1 := context.WithCancel(parentCtx)
    defer childCancel1()
    
    // 子context2
    childCtx2, childCancel2 := context.WithTimeout(parentCtx, 5*time.Second)
    defer childCancel2()
    
    // 孙context
    grandChildCtx, grandChildCancel := context.WithCancel(childCtx1)
    defer grandChildCancel()
    
    // 启动监听各个context的goroutine
    var wg sync.WaitGroup
    
    contexts := []struct {
        name string
        ctx  context.Context
    }{
        {"父context", parentCtx},
        {"子context1", childCtx1},
        {"子context2", childCtx2},
        {"孙context", grandChildCtx},
    }
    
    for _, c := range contexts {
        wg.Add(1)
        go func(name string, ctx context.Context) {
            defer wg.Done()
            
            <-ctx.Done()
            fmt.Printf("%s 被取消: %v\n", name, ctx.Err())
        }(c.name, c.ctx)
    }
    
    // 2秒后取消父context
    time.Sleep(2 * time.Second)
    fmt.Println("取消父context...")
    parentCancel()
    
    wg.Wait()
}

// 5. Context与select的配合使用
func contextWithSelect() {
    fmt.Println("\n=== Context与Select配合使用 ===")
    
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    
    // 数据channel
    data := make(chan string, 1)
    
    // 启动数据生产者
    go func() {
        time.Sleep(2 * time.Second)
        data <- "重要数据"
    }()
    
    // 使用select等待数据或超时
    select {
    case result := <-data:
        fmt.Printf("收到数据: %s\n", result)
    case <-ctx.Done():
        fmt.Printf("操作超时: %v\n", ctx.Err())
    case <-time.After(1 * time.Second):
        fmt.Println("1秒内没有收到数据,但继续等待...")
        
        // 继续等待
        select {
        case result := <-data:
            fmt.Printf("最终收到数据: %s\n", result)
        case <-ctx.Done():
            fmt.Printf("最终超时: %v\n", ctx.Err())
        }
    }
}

func main() {
    // 1. 可取消的工作池示例
    fmt.Println("=== 可取消的工作池 ===")
    
    pool := NewCancellableWorkerPool(3)
    pool.Start()
    
    // 提交任务
    for i := 1; i <= 10; i++ {
        taskID := i
        pool.Submit(func(ctx context.Context) error {
            select {
            case <-time.After(time.Duration(taskID*200) * time.Millisecond):
                fmt.Printf("任务 %d 完成\n", taskID)
                return nil
            case <-ctx.Done():
                fmt.Printf("任务 %d 被取消\n", taskID)
                return ctx.Err()
            }
        })
    }
    
    // 2秒后取消所有任务
    time.Sleep(2 * time.Second)
    fmt.Println("取消所有任务...")
    pool.Cancel()
    
    // 收集结果
    go func() {
        for err := range pool.Results() {
            if err != nil {
                fmt.Printf("任务错误: %v\n", err)
            }
        }
    }()
    
    pool.Close()
    
    httpClientWithTimeout()
    databaseTransactionTimeout()
    cascadingCancellation()
    contextWithSelect()
}

总结

  1. Context类型

    • context.Background() - 根context
    • context.TODO() - 占位符context
    • context.WithCancel() - 可取消context
    • context.WithTimeout() - 超时context
    • context.WithDeadline() - 截止时间context
  2. Context传值

    • 使用context.WithValue()传递请求范围的数据
    • 使用自定义类型作为key避免冲突
    • 提供类型安全的访问函数
    • 只存储请求相关数据,不存储可选参数
  3. 取消传播

    • 父context取消时,所有子context自动取消
    • 使用ctx.Done()检查取消状态
    • 使用ctx.Err()获取取消原因
    • 及时释放资源,调用cancel函数
  4. 超时处理

    • 为长时间操作设置合理超时
    • 在select中使用<-ctx.Done()
    • 区分超时和取消错误
    • 优雅处理超时情况
  5. 最佳实践

    • Context应该作为函数的第一个参数
    • 不要在结构体中存储Context
    • 不要传递nil Context,使用context.TODO()
    • Context是并发安全的,可以在多个goroutine中使用
    • 使用defer确保cancel函数被调用
updatedupdated2025-09-202025-09-20