Cloudgeek Reading source series-cache2go Source code Analysis

Source: Internet
Author: User

First, what is Cache2go?
    • The author says: Concurrency-safe Golang caching Library with expiration capabilities.

What do you mean?

    • Concurrency-Safe Go language cache library with heartbeat mechanism

A good way to learn a language is to read the source of excellent open source projects, learn the code of excellent predecessors, while discovering their own knowledge blind zone, and constantly acquire new knowledge! Cache2go is very concise, the code is very small, very suitable for the first contact with the Go language students as an entry-level project to read the source.

Next I will introduce the project composition, then explain the core data structure, and then comb the entire implementation logic, to help you master the whole project.

II. Structure of the project

Project directory structure as shown, you can see the function implementation of the relevant source files only 3:

    1. Cache.go
    2. Cacheitem.go
    3. Cachetable.go
III. Key Data Structures

Only 2 complex data types are involved in the project, namely:

    1. CacheItem
    2. Cachetable

The meaning is consistent with the literal meaning, one is the cache table, and the other is the entry in the cache table. Let's look at how the 2 structures are defined below.

1, CacheItem

The CacheItem type is used to represent a separate cache entry, the source code is shown below, each field is clearly understandable, and a slightly longer note has been annotated in Chinese.

Type CacheItem struct {sync. rwmutex//the item ' s Key.key interface{}//the item ' s Data.data interface{}//how long would the item live in the cache whe N not being accessed/kept alive. "Survive without access" lifespan time. duration//Creation Timestamp.createdon time. time//last access Timestamp.accessedon time. time//how often the item is Accessed.accesscount int64//Callback method triggered right before removing the item from T Abouttoexpire func (Key interface{}) "The callback method triggered when the he cache was deleted"
2, Cachetable

Cachetable describes a table entry in the cache, with the Items property being the CacheItem type instance mentioned above. In addition to the general properties, there are several function type properties, the source code is as follows:

Type cachetable struct {sync. rwmutex//the table ' s name.name string//all cached items. "In this map, all the entries in a table, the map key is any type, the value is the CacheItem pointer type" items map[ interface{}]*cacheitem//timer responsible for triggering cleanup. "Timers responsible for triggering cleanup operations" Cleanuptimer *time. timer//Current timer duration. "Cleanup action triggered interval" CleanupInterval time. duration//the logger used for this table.logger *log. logger//Callback method triggered when trying to load a non-existing key. "Callback function triggered when a nonexistent key needs to be extracted" loaddata func (Key Interfa ce{}, args ... interface{}) *cacheitem//Callback method triggered when adding a new item to the cache. "Callback function triggered when a cache entry is added" ad Deditem func (item *cacheitem)//Callback method triggered before deleting an item from the cache. "Callback function triggered before deletion" abouttodelete Item func (item *cacheitem)}

As shown above, Cache2go's core data structure is concise and should be easier to understand. Of course, not fully understand the reason for the definition of each field is not urgent, after reading the following code logic in turn to look at the data structure, it is certain to understand the role of each field.

Iv. Code Logic

Our idea is to analyze the code from the bottom up, what does it mean? This means looking at the action associated with the item, then the table-related code that contains the item, and finally the logic to manipulate the cache level of the table. So the following we have to look at Cacheitem.go code, then analyze Cachetable.go, and then see Cache.go, and finally see the 3 files in the source of the correlation between what is.

1, Cacheitem.go

For example, this source file contains only a definition of type CacheItem and a function Newcacheitem (). CacheItem What properties have been seen before, the following first look at the Newcacheitem () function:

Func Newcacheitem (Key interface{}, lifespan time. Duration, Data interface{}) *cacheitem {t: = time. Now () return &cacheitem{key:           key,lifespan:      lifespan,createdon:     t,accessedon:    t,accesscount:   0,abouttoexpire:nil,data:          data,}}
    • As shown above, the Newcacheitem () function receives 3 parameters, namely, the key, the value, the time to live (key, data, lifespan), and returns a pointer to an instance of the CacheItem type.
    • Where Createon and Accessedon are set to the current time, Abouttoexpire is the callback method triggered when the deletion is temporarily set to nil, it is not difficult to think that this function will need to call other methods to set this property.

Cacheitem.go In addition to the definition of the CacheItem type, the definition of the Newcacheitem () function, there is a part of the CacheItem method definition, a total of 8

The source code looks a lot of lines, the content is actually very simple, the main element is to get the operation, here need to pay attention to read and write operations are added the corresponding read and write lock, remember the beginning of the cache2go is a concurrency security program? Concurrency security is reflected in these places. The most complex of the following is the setting of the last callback function, the formal parameter of this method is F func (interface{}), that is, the formal parameter name is F, the formal parameter type is func (interface{}), which is a function type, the parameter of the function type is a interface{ }, which is an empty interface, because any type can be considered to implement an empty interface, so you can receive any type of argument here. That is, the type of f is a function type that can receive any type of argument. A bit around, need to calm down to understand oh ~

The source code is as follows:

KeepAlive marks an item to is kept for another expireduration period. "Update Accessedon to Current Time" func (item *cacheitem) Keepali ve () {Item. Lock () defer item. Unlock () Item.accessedon = time. Now () item.accesscount++}//lifespan returns this item ' s expiration duration.func (item *cacheitem) lifespan () time. Duration {//Immutablereturn item.lifespan}//Accessedon returns when this item is last Accessed.func (item *cacheitem) A Ccessedon () time. Time {item. Rlock () defer item. Runlock () return item.accessedon}//CreatedOn returns when this item is added to the Cache.func (item *cacheitem) Createdo N () time. Time {//Immutablereturn item.createdon}//Accesscount returns how to often this item has been ACCESSED.FUNC (item *cacheitem ) Accesscount () Int64 {item. Rlock () defer item. Runlock () Return item.accesscount}//key returns the key of this cached Item.func (item *cacheitem) key () interface{} {//I Mmutablereturn item.key}//Data Returns the value of this cached Item.func (item *cacheitem) data () interface{} {// Immutablereturn item.data}//Setabouttoexpirecallback configures a callback, which would be called right//before the item is about to being removed from the cache. "Set the callback function that will be called when an item is removed" func (item *cacheitem) Setabouttoexpirecallback (f Fun C (interface{})) {item. Lock () defer item. Unlock () Item.abouttoexpire = f}

Here to read this source file, is not very easy ~

Below continue to see the other 2 source files.

2, Cachetable.go3, Cache.go

AbouttoexpireDetailXNo English-Chinese translation results
Please try Web search

Cloudgeek Reading source series-cache2go Source code Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.