polarisxu
polarisxu copied to clipboard
posts/go/pkg/singleflight-generic/
func fetchArticle(id int) *Article {
article := findArticleFromCache(id)
if article != nil && article.ID > 0 {
return article
}
if rand.Intn(100) > 50 { //在执行Do()之前,可以随机让协程sleep。可以看到,因为没有double check,只是用singleflight还是有可能多次执行下游的select
time.Sleep(time.Second)
}
...
}
Output:
2022/11/14 23:05:42 SELECT * FROM article WHERE id=1
shared=== true
2022/11/14 23:05:42 &{1 polarisxu}
shared=== true
2022/11/14 23:05:42 &{1 polarisxu}
2022/11/14 23:05:43 SELECT * FROM article WHERE id=1
shared=== true
2022/11/14 23:05:43 &{1 polarisxu}
shared=== true
2022/11/14 23:05:43 &{1 polarisxu}
shared=== true
2022/11/14 23:05:43 &{1 polarisxu}