问题:并发获取数据的时候超过一个请求访问到数据库了
环境:8核cpu,centos7,go1.14
代码:
package main
import (
"errors"
"log"
"sync"
"golang.org/x/sync/singleflight"
)
var errorNotExist = errors.New("not exist")
var g singleflight.Group
func main() {
var wg sync.WaitGroup
cpu_amount := 4
wg.Add(cpu_amount)
for i := 0; i < cpu_amount; i++ {
go func() {
defer wg.Done()
data, err := getData("key")
if err != nil {
log.Print(err)
return
}
log.Println(data)
}()
}
wg.Wait()
}
func getData(key string) (string, error) {
data, err := getDataFromCache(key)
if err == errorNotExist {
v, err, _ := g.Do(key, func() (interface{}, error) {
return getDataFromDB(key)
})
if err != nil {
log.Println(err)
return "", err
}
data = v.(string)
} else if err != nil {
return "", err
}
return data, nil
}
func getDataFromCache(key string) (string, error) {
return "", errorNotExist
}
func getDataFromDB(key string) (string, error) {
log.Printf("get %s from database", key)
return "data", nil
}
执行结果1:
执行结果2:
执行结果3:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…