Go Context用法总结

182 阅读1分钟

1. context.Background

  • 作用:作为根 Context,通常在 main 函数、初始化时使用。
  • 特点:不会被取消、不携带值,为空的上下文。

2. context.TODO

  • 作用:当不确定使用哪种 Context 时的占位符,表示“待定”。
  • 特点:与 Background 功能相同,但语义上表示需要后续调整。

3. context.WithTimeout

  • 作用:创建一个带有超时限制的 Context,适用于需要限定操作时长的场景。
  • 特点
    • 超时后自动取消,防止操作无限期挂起。
    • 返回 cancel 函数,用于在超时前手动取消。

示例:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

4. context.WithDeadline

  • 作用:与 WithTimeout 类似,但基于绝对截止时间来取消 Context。
  • 特点:当系统时间达到截止时间时,Context 自动取消。

示例:

deadline := time.Now().Add(5 * time.Second)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()

5. context.WithCancel

  • 作用:创建一个可手动取消的 Context,适用于需要主动终止的场景。
  • 特点
    • 返回 cancel 函数,可在任何时候调用 cancel() 主动取消。

示例:

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

6. context.WithValue

  • 作用:在 Context 中传递键值对数据,适用于请求相关的数据传递。
  • 特点
    • 适合传递少量数据,如请求 ID、用户信息。
    • 不建议 过度使用来传递业务逻辑参数。

示例:

ctx := context.WithValue(context.Background(), "userID", 12345)

总结

方法作用适用场景
context.Background作为根 Contextmain、初始化
context.TODO占位符 Context不确定使用哪种 Context
context.WithTimeout限定操作时长需要超时控制
context.WithDeadline限定截止时间需要固定时间点取消
context.WithCancel可手动取消需要主动终止的操作
context.WithValue传递键值数据请求上下文数据传递

这些方法可结合使用,帮助 Go 程序在并发环境下更好地管理超时、取消信号和数据传递。