昨天突然接到報警說服務端口丟失,也就是服務崩潰,看了錯誤日志,發現是map並發讀寫問題,記錄下來,避免再犯類似錯誤。
分析錯誤日志
發現是調用json.Marshal時出錯了,錯誤統計如下,都是並發讀寫map之類的異常。
229次錯誤:fatal error: concurrent map iteration and map write
193次錯誤:fatal error: concurrent map writes
129次錯誤:fatal error: concurrent map read and map write
xxx/xxx.go文件的114行:
func getFeatureMap(ctx context.Context, filters []*model.FiltersType, driverId int64) map[string]string {
var features []string
for _, filterRule := range filters {
param := filterRule.FilterMap
param["driver_id"] = strconv.FormatInt(driverId, 10)
featureKeys, _ := ufs.BuildKeyList(domain, []string{key}, param) // 114行
features = append(features, featureKeys...)
}
...
}
看起來就是傳入的param這個map被多個協程並發寫了,filterRule.FilterMap是全局變量,所以這里需要修改為深拷貝。
深拷貝的函數
// DeepCopyMap map[string]string 類型實現深拷貝
func DeepCopyMap(params map[string]string) map[string]string {
result := map[string]string{}
for k, v := range params {
result[k] = v
}
return result
}
調用深拷貝實現
把param := filterRule.FilterMap
修改為 param := DeepCopyMap(filterRule.FilterMap)
一個簡單的模擬示例
package main
import (
"encoding/json"
"fmt"
"math/rand"
"strconv"
"sync"
"time"
)
func main() {
param := map[string]string{
"name": "andy",
"age": "30",
}
f := func(i int) {
tempMap := param
//tempMap := DeepCopyMap(m) // 使用深度拷貝可以解決並發讀寫map的問題
tempMap["idx"] = strconv.Itoa(i)
time.Sleep(time.Millisecond * time.Duration(rand.Intn(10)))
json.Marshal(tempMap)
}
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
f(idx)
}(i)
}
wg.Wait()
fmt.Println("Finish")
}
// DeepCopyMap map[string]string 類型實現深拷貝
func DeepCopyMap(params map[string]string) map[string]string {
result := map[string]string{}
for k, v := range params {
result[k] = v
}
return result
}
執行上述代碼,很容易報以下其中一個或多個的錯誤。
- fatal error: concurrent map iteration and map write
- fatal error: concurrent map writes
- fatal error: concurrent map read and map write