【Golang】groupcache之singleflight

Introduction to groupcache

github.com/golang/groupcache

Groupcache is a caching and cache-filling library used in many cases as a replacement for Memcached.

groupcache is an open source project by the author of memcache, and in many cases, it is a replacement for memcached.

groupcache does not support updating or deleting, and the loading of data is operated through the GetterFunc function.
groupcache is suitable for scenarios with high performance requirements and no data updates.

Introduction to singleflight

In the case of high concurrency, when a large number of requests query the same key at the same time, the key just fails at this time, which will cause all these requests to query the database at the same time, and it is easy to collapse the database. This phenomenon is called Cache breakdown.
There is a singleflight module in groupcache, and with 65 lines of code commented, its functions are more powerful, and it solves the problem of cache breakdown.

package main
import (
"github.com/golang/groupcache/singleflight"
"github.com/patrickmn/go-cache"
)
	
var gc *cache.Cache
var sg singleflight.Group
var once sync.Once

func gcInstance() *cache.Cache {
	once.Do(func() {
		defaultExpiration := 10 * time.Minute
		cleanupInterval := 5 * time.Minute
		gc = cache.New(defaultExpiration, cleanupInterval)
	})
	return gc
}

func testCache(typeId int) (list []someModel) {
	key := fmt.Sprintf("test_%d", typeId)
	list2, exists := gcInstance().Get(key)
	if !exists {
		fn := func() (interface{}, error) {
			var list3 []someModel
			model.Where("type_id=? ", typeId.Find(&list3)
			gcInstance().Set(key, list3, 0)
			return list3, nil
		}
		list2, _ = sg.Do(key, fn)
	}

	list = list2.([]someModel)

	return
}

References

Guess you like

Origin blog.csdn.net/Kevin_Gates/article/details/130100729