The go-zero microservices framework provides many out-of-the-box tools, good tools can not only improve the performance of the service but also improve the robustness of the code to avoid errors, to achieve a uniform style of code for others to read, etc. This series of articles will introduce the use of the go-zero framework tools and their implementation principles
When doing server development, I believe we will encounter the use of cache, go-zero provides a simple cache package collection.Cache, simple to use as follows
The built features implemented by cache include
- automatic cache expiration, you can specify the expiration time
- Cache size limit, you can specify the number of caches
- cache add, delete and change
- Cache hit rate statistics
- Concurrency security
- Cache hitting
Implementation principle. Cache automatic invalidation is managed using TimingWheel
Cache size limit, is the use of LRU elimination policy, when the new cache will check whether the limit has been exceeded, the specific code in the keyLru implementation
Cache hit statistics are implemented in code as cacheStat, which automatically counts when a cache hit is lost and prints the status of hits, qps, etc. used at regular intervals.
The printout will look like this
Cache hit containment is implemented using syncx.SingleFlight, which is a request for the same key at the same time, SingleFlight(), which will request the same key at the same time, will be added later. The specific implementation is described in:
This article introduces the Cache tool in the go-zero framework, which is very useful in real projects. Using good tools for improving service performance and development efficiency are very helpful, I hope this article can bring you some gains.