golang在http.Request中提供了一个Context用于存储kv对,咱们能够经过这个来存储请求相关的数据。在请求入口,咱们把惟一的requstID存储到context中,在后续须要调用的地方把值取出来打印。若是日志是在controller中打印,这个很好处理,http.Request是做为入参的。但若是是在更底层呢?好比说是在model甚至是一些工具类中。咱们固然能够给每一个方法都提供一个参数,由调用方把context一层一层传下来,但这种方式明显不够优雅。想一想java里面是怎么作的--ThreadLocal。虽然golang官方不太承认这种方式,可是咱们今天就是要基于goroutine id实现它。java
We wouldn't even be having this discussion if thread local storage wasn't useful. But every feature comes at a cost, and in my opinion the cost of threadlocals far outweighs their benefits. They're just not a good fit for Go.
每一个goroutine有一个惟一的id,可是被隐藏了,咱们首先把它暴露出来,而后创建一个map,用id做为key,goroutineLocal存储的实际数据做为value。golang
1.修改 $GOROOT/src/runtime/proc.go 文件,添加 GetGoroutineId() 函数bash
func GetGoroutineId() int64 { return getg().goid }
其中getg()函数是获取当前执行的g对象,g对象包含了栈,cgo信息,GC信息,goid等相关数据,goid就是咱们想要的。函数
2.从新编译源码工具
cd ~/go/src GOROOT_BOOTSTRAP='/Users/qiuxudong/go1.9' ./all.bash
package goroutine_local import ( "sync" "runtime" ) type goroutineLocal struct { initfun func() interface{} m *sync.Map } func NewGoroutineLocal(initfun func() interface{}) *goroutineLocal { return &goroutineLocal{initfun:initfun, m:&sync.Map{}} } func (gl *goroutineLocal)Get() interface{} { value, ok := gl.m.Load(runtime.GetGoroutineId()) if !ok && gl.initfun != nil { value = gl.initfun() } return value } func (gl *goroutineLocal)Set(v interface{}) { gl.m.Store(runtime.GetGoroutineId(), v) } func (gl *goroutineLocal)Remove() { gl.m.Delete(runtime.GetGoroutineId()) }
简单测试一下测试
package goroutine_local import ( "testing" "fmt" "time" "runtime" ) var gl = NewGoroutineLocal(func() interface{} { return "default" }) func TestGoroutineLocal(t *testing.T) { gl.Set("test0") fmt.Println(runtime.GetGoroutineId(), gl.Get()) go func() { gl.Set("test1") fmt.Println(runtime.GetGoroutineId(), gl.Get()) gl.Remove() fmt.Println(runtime.GetGoroutineId(), gl.Get()) }() time.Sleep(2 * time.Second) }
能够看到结果this
5 test0 6 test1 6 default
因为跟goroutine绑定的数据放在goroutineLocal的map里面,即便goroutine销毁了数据还在,可能存在内存泄露,所以不使用时要记得调用Remove清除数据日志