polarisxu icon indicating copy to clipboard operation
polarisxu copied to clipboard

posts/go/pkg/singleflight-generic/

Open utterances-bot opened this issue 2 years ago • 1 comments

泛型版 singleflight:Go 中如何防止缓存击穿?

https://polarisxu.studygolang.com/posts/go/pkg/singleflight-generic/

utterances-bot avatar Nov 14 '22 15:11 utterances-bot

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}

wanzirong avatar Nov 14 '22 15:11 wanzirong