開篇
golang在http.Request中提供了一個(gè)Context用于存儲(chǔ)kv對,我們可以通過這個(gè)來存儲(chǔ)請求相關(guān)的數(shù)據(jù)。在請求入口摊册,我們把唯一的requstID存儲(chǔ)到context中,在后續(xù)需要調(diào)用的地方把值取出來打印颊艳。如果日志是在controller中打印丧靡,這個(gè)很好處理,http.Request是作為入?yún)⒌淖严尽5绻窃诟讓幽匚轮危勘热缯f是在model甚至是一些工具類中。我們當(dāng)然可以給每個(gè)方法都提供一個(gè)參數(shù)戒悠,由調(diào)用方把context一層一層傳下來熬荆,但這種方式明顯不夠優(yōu)雅。想想java里面是怎么做的--ThreadLocal绸狐。雖然golang官方不太認(rèn)可這種方式卤恳,但是我們今天就是要基于goroutine id實(shí)現(xiàn)它累盗。
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.
思路
每個(gè)goroutine有一個(gè)唯一的id,但是被隱藏了突琳,我們首先把它暴露出來若债,然后建立一個(gè)map,用id作為key拆融,goroutineLocal存儲(chǔ)的實(shí)際數(shù)據(jù)作為value蠢琳。
獲取goroutine id
1.修改 $GOROOT/src/runtime/proc.go 文件,添加 GetGoroutineId() 函數(shù)
func GetGoroutineId() int64 {
return getg().goid
}
其中g(shù)etg()函數(shù)是獲取當(dāng)前執(zhí)行的g對象镜豹,g對象包含了棧傲须,cgo信息,GC信息趟脂,goid等相關(guān)數(shù)據(jù)泰讽,goid就是我們想要的。
2.重新編譯源碼
cd ~/go/src
GOROOT_BOOTSTRAP='/Users/qiuxudong/go1.9' ./all.bash
實(shí)現(xiàn) GoroutineLocal
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)
}
可以看到結(jié)果
5 test0
6 test1
6 default
內(nèi)存泄露問題
由于跟goroutine綁定的數(shù)據(jù)放在goroutineLocal的map里面昔期,即使goroutine銷毀了數(shù)據(jù)還在已卸,可能存在內(nèi)存泄露,因此不使用時(shí)要記得調(diào)用Remove清除數(shù)據(jù)