This is a creation in Article, where the information may have evolved or changed.
Learn about the open source cache library, Cache2g0 is a more accessible library for Go beginners.
Cache2go
Concurrency-safe Golang caching library with expiration capabilities.
Cache2g0 is a key-value-format cache library that guarantees concurrency and security with expiration control.
How do you design a cache library?
The most convenient way: the Key-value form. Like Redis, I first draw a table and then store n key-value in the table.
Cache_design.png
Cache2go implementation is the implementation of the principle, based on the addition of security and expiration control and other functions.
Some Cache2go source interpretation
First let's look at the structure of the Cache2go: Cachetable,cacheitem
//cachetabletype cachetable struct {sync. Rwmutex//Mutex name string//table name items The collection of Map[interface{}]*cacheitem//item Cleanuptimer *time. Timer//Set cleanup time (waiting state) CleanupInterval. Duration//Set scavenging time period logger *log. Logger//Set Log loaddata func (Key interface{}, args ... interface{}) *cacheitem Addeditem Func (item *cacheitem) Abouttodeleteitem func (item *cacheitem)}//cacheitemtype CacheItem struct {sync. Rwmutex//Mutual Exclusion lock key interface{}//Data-key data interface{} Data-value lifespan time. Duration//life cycle CreatedOn time. Time//creation times Accessedon. Time//Last access Accesscount Int64//number of visits Abouttoexpire func (key interface{})//todo}< /code>
In order to guarantee its concurrency security, it has the sync.RWMutex
atomicity of maintaining the operation. And with timestamps to achieve expiration control. As for the callback functions, I also saw this writing for the first time.
Cache2go Authors, according to these two structs open a number of getter&setter
methods, the user only need to call, the code implementation process also has to determine whether users have set properties, to ensure the robustness of the program.
As an example:
The cachetable contains the Logger field and is written SetLogger(logger)
to allow the user to implement logger printing and implement the log (v ...). method, which allows the user to implement Setlogger (logger), and does not need to be called if the user does not want to print the log SetLogger(logger)
.
func (table *CacheTable) log(v ...interface{}) { if table.logger == nil { return } table.logger.Println(v)}
Create a table and add item
By creating a cache table and adding the cache item to parse the source code, the implementation is as follows:
// new Cache cache := cache2go.Cache("myCache") // set logger logger := log.New(os.Stdout, "DEBUG", log.Ltime) cache.SetLogger(logger) // will storage data val := myStruct{"This is a test!", []byte{}} // Add Item : key, duration, stor_data cache.Add("someKey", 5*time.Second, &val)
Create a table
cache2go Call Cache(tableName)
method to implement the creation, the internal use of map to achieve, first through the tableName
keyword in the map to find, if there is a direct return, otherwise first out created, and then returned.
Cache
Add a cacheitem to the table
NewCacheItem(key, lifeSpan, value)
completion of CacheItem initialization by invocation
- Next you need to add CacheItem to cachetable
- Cachetable objects are added by calling their own
addInternal(cacheItem)
completion and checking for outdated caches
addInternal(cacheItem)
call itself in expiraionCheck()
to complete the check.
Add.png
This is just a simple description of the code below, the main master of its design ideas is good. For further details, please visit cache2g0
Knowledge points that need to be expanded (subsequent updates ...)
- Callback functions in a struct
- Sync. Interpretation of Rwmutex Source code
- Interpretation of Time source code
Great articles, continuous updates, please pay attention to the public number:
Handsome beauty sweep