package main
import (
"golang.org/x/sync/singleflight"
"log"
"time"
)
func main() {
var singleSetCache singleflight.Group
getAndSetCache := func(requestID int, cacheKey string) (string, error) {
value, _, _ := singleSetCache.Do(cacheKey, func() (ret interface{}, err error) { //do的入参key,可以直接使用缓存的key,这样同一个缓存,只有一个协程会去读DB
log.Printf("requestid执行一次 %v ", requestID)
return "VALUE", nil
})
return value.(string), nil
}
cacheKey := "cacheKey"
for i := 1; i < 10; i++ { //模拟多个协程同时请求
go func(requestID int) {
value, _ := getAndSetCache(requestID, cacheKey)
//_ = value
log.Printf("requestID %v get 值: %v", requestID, value)
}(i)
}
time.Sleep(20 * time.Second)
}
golang 并发缓存击穿或合并请求
最新推荐文章于 2024-03-14 17:34:26 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)