使用 context.withvalue 时,需注意以下要点:1. 使用私有类型作为 key 避免冲突;2. 传递不可变值,确保线程安全;3. 避免频繁创建 context;4. 不适合存储可变对象、大量数据或替代函数参数。正确做法是在请求开始时构造好 metadata,并通过参数传递 context。
在使用 Golang 的
context
context.WithValue
context.WithValue
它的使用方式很简单:
立即学习“go语言免费学习笔记(深入)”;
ctx := context.WithValue(parentCtx, key, value)
其中
key
举个例子:
type keyType string const userIDKey keyType = "user_id" ctx := context.WithValue(context.Background(), userIDKey, "12345")
然后在其他地方通过
ctx.Value(userIDKey)
这个问题的答案是:只要你不修改上下文对象本身,就是线程安全的。
因为
context
WithValue
但是要注意:
所以正确的做法是:
为了避免 key 冲突,推荐的做法是:
string
"user_id"
示例:
type keyType int const ( userIDKey keyType = iota traceIDKey ) ctx := context.WithValue(ctx, userIDKey, "123") ctx = context.WithValue(ctx, traceIDKey, "abc")
这样即使两个不同的包都用了
iota
不适合的场景包括:
基本上就这些。合理使用
context.WithValue
以上就是Golang的context如何传递元数据 讲解WithValue的线程安全用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号