cache2go

package module
v0.0.0-...-0c95a62 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2019 License: BSD-3-Clause Imports: 5 Imported by: 0

README

cache2go

源码分析文档见: 源码分析-cache2go

Concurrency-safe golang caching library with expiration capabilities.

Installation

Make sure you have a working Go environment (Go 1.2 or higher is required). See the install instructions.

To install cache2go, simply run:

go get github.com/muesli/cache2go

To compile it from source:

cd $GOPATH/src/github.com/muesli/cache2go
go get -u -v
go build && go test -v

Example

package main

import (
	"github.com/muesli/cache2go"
	"fmt"
	"time"
)

// Keys & values in cache2go can be of arbitrary types, e.g. a struct.
type myStruct struct {
	text     string
	moreData []byte
}

func main() {
	// Accessing a new cache table for the first time will create it.
	cache := cache2go.Cache("myCache")

	// We will put a new item in the cache. It will expire after
	// not being accessed via Value(key) for more than 5 seconds.
	val := myStruct{"This is a test!", []byte{}}
	cache.Add("someKey", 5*time.Second, &val)

	// Let's retrieve the item from the cache.
	res, err := cache.Value("someKey")
	if err == nil {
		fmt.Println("Found value in cache:", res.Data().(*myStruct).text)
	} else {
		fmt.Println("Error retrieving value from cache:", err)
	}

	// Wait for the item to expire in cache.
	time.Sleep(6 * time.Second)
	res, err = cache.Value("someKey")
	if err != nil {
		fmt.Println("Item is not cached (anymore).")
	}

	// Add another item that never expires.
	cache.Add("someKey", 0, &val)

	// cache2go supports a few handy callbacks and loading mechanisms.
	cache.SetAboutToDeleteItemCallback(func(e *cache2go.CacheItem) {
		fmt.Println("Deleting:", e.Key(), e.Data().(*myStruct).text, e.CreatedOn())
	})

	// Remove the item from the cache.
	cache.Delete("someKey")

	// And wipe the entire cache table.
	cache.Flush()
}

To run this example, go to examples/mycachedapp/ and run:

go run mycachedapp.go

You can find a few more examples here. Also see our test-cases in cache_test.go for further working examples.

Development

GoDoc Build Status Coverage Status Go ReportCard

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrKeyNotFound gets returned when a specific key couldn't be found
	ErrKeyNotFound = errors.New("Key not found in cache")
	// ErrKeyNotFoundOrLoadable gets returned when a specific key couldn't be
	// found and loading via the data-loader callback also failed
	ErrKeyNotFoundOrLoadable = errors.New("Key not found and could not be loaded into cache")
)

Functions

This section is empty.

Types

type CacheItem

type CacheItem struct {
	// 【读写锁,保证CacheItem同步访问】
	sync.RWMutex
	// contains filtered or unexported fields
}

CacheItem is an individual cache item Parameter data contains the user-set value in the cache. 【CacheItem是单个的缓存条目, 也就是一个key-value缓存数据】

func NewCacheItem

func NewCacheItem(key interface{}, lifeSpan time.Duration, data interface{}) *CacheItem

NewCacheItem returns a newly created CacheItem. Parameter key is the item's cache-key. Parameter lifeSpan determines after which time period without an access the item will get removed from the cache. Parameter data is the item's value. 【创建CacheItem】

func (*CacheItem) AccessCount

func (item *CacheItem) AccessCount() int64

AccessCount returns how often this item has been accessed. 【返回accessCount】

func (*CacheItem) AccessedOn

func (item *CacheItem) AccessedOn() time.Time

AccessedOn returns when this item was last accessed. 【返回accessedOn】

func (*CacheItem) AddAboutToExpireCallback

func (item *CacheItem) AddAboutToExpireCallback(f func(interface{}))

AddAboutToExpireCallback appends a new callback to the AboutToExpire queue 【添加被移除时候的回调函数】

func (*CacheItem) CreatedOn

func (item *CacheItem) CreatedOn() time.Time

CreatedOn returns when this item was added to the cache. 【返回createdOn】

func (*CacheItem) Data

func (item *CacheItem) Data() interface{}

Data returns the value of this cached item. 【返回data】

func (*CacheItem) KeepAlive

func (item *CacheItem) KeepAlive()

KeepAlive marks an item to be kept for another expireDuration period. 【重置过期时间, 需要加锁(下面类似的不再说)】

func (*CacheItem) Key

func (item *CacheItem) Key() interface{}

Key returns the key of this cached item. 【返回key】

func (*CacheItem) LifeSpan

func (item *CacheItem) LifeSpan() time.Duration

LifeSpan returns this item's expiration duration. 【返回lifeSpan, 不需要加锁, 因为创建后就没有情况会修改此值(下面类似的不再说)】

func (*CacheItem) RemoveAboutToExpireCallback

func (item *CacheItem) RemoveAboutToExpireCallback()

RemoveAboutToExpireCallback empties the about to expire callback queue 【删除被移除时候的回调函数】

func (*CacheItem) SetAboutToExpireCallback

func (item *CacheItem) SetAboutToExpireCallback(f func(interface{}))

SetAboutToExpireCallback configures a callback, which will be called right before the item is about to be removed from the cache. 【设置被移除时候的回调函数】

type CacheItemPair

type CacheItemPair struct {
	Key         interface{}
	AccessCount int64
}

CacheItemPair maps key to access counter 【缓存条目对】

type CacheItemPairList

type CacheItemPairList []CacheItemPair

CacheItemPairList is a slice of CacheIemPairs that implements sort. Interface to sort by AccessCount. 【缓存条目对切片】

func (CacheItemPairList) Len

func (p CacheItemPairList) Len() int

func (CacheItemPairList) Less

func (p CacheItemPairList) Less(i, j int) bool

func (CacheItemPairList) Swap

func (p CacheItemPairList) Swap(i, j int)

【qsort需要的一些函数, 根据访问次数排序】

type CacheTable

type CacheTable struct {
	// 【读写锁,保证CacheItem同步访问】
	sync.RWMutex
	// contains filtered or unexported fields
}

CacheTable is a table within the cache 【缓存表, 】

func Cache

func Cache(table string) *CacheTable

Cache returns the existing cache table with given name or creates a new one if the table does not exist yet. 【创建缓存】

func (*CacheTable) Add

func (table *CacheTable) Add(key interface{}, lifeSpan time.Duration, data interface{}) *CacheItem

Add adds a key/value pair to the cache. Parameter key is the item's cache-key. Parameter lifeSpan determines after which time period without an access the item will get removed from the cache. Parameter data is the item's value. 【添加缓存条目到缓存表中, addInternal会释放锁】

func (*CacheTable) AddAboutToDeleteItemCallback

func (table *CacheTable) AddAboutToDeleteItemCallback(f func(*CacheItem))

AddAboutToDeleteItemCallback appends a new callback to the AboutToDeleteItem queue 【添加删除缓存条目时触发的回调函数】

func (*CacheTable) AddAddedItemCallback

func (table *CacheTable) AddAddedItemCallback(f func(*CacheItem))

AddAddedItemCallback appends a new callback to the addedItem queue 【添加添加缓存条目时触发的回调函数】

func (*CacheTable) Count

func (table *CacheTable) Count() int

Count returns how many items are currently stored in the cache. 【返回缓存条目的数量】

func (*CacheTable) Delete

func (table *CacheTable) Delete(key interface{}) (*CacheItem, error)

Delete an item from the cache. 【从缓存表中删除缓存条目, addInternal会释放锁】

func (*CacheTable) Exists

func (table *CacheTable) Exists(key interface{}) bool

Exists returns whether an item exists in the cache. Unlike the Value method Exists neither tries to fetch data via the loadData callback nor does it keep the item alive in the cache. 【是否存在某个key】

func (*CacheTable) Flush

func (table *CacheTable) Flush()

Flush deletes all items from this cache table. 【清除所有的缓存条目, 不会调用 缓存表的aboutToDeleteItem 和 缓存条目的aboutToExpire 】

func (*CacheTable) Foreach

func (table *CacheTable) Foreach(trans func(key interface{}, item *CacheItem))

Foreach all items 【遍历缓存条目】

func (*CacheTable) MostAccessed

func (table *CacheTable) MostAccessed(count int64) []*CacheItem

MostAccessed returns the most accessed items in this cache table 【获取访问最多的几个CacheItem, 最多访问count个】

func (*CacheTable) NotFoundAdd

func (table *CacheTable) NotFoundAdd(key interface{}, lifeSpan time.Duration, data interface{}) bool

NotFoundAdd tests whether an item not found in the cache. Unlike the Exists method this also adds data if they key could not be found. 【不存在才添加】

func (*CacheTable) RemoveAboutToDeleteItemCallback

func (table *CacheTable) RemoveAboutToDeleteItemCallback()

RemoveAboutToDeleteItemCallback empties the about to delete item callback queue 【删除删除缓存条目时触发的回调函数】

func (*CacheTable) RemoveAddedItemCallbacks

func (table *CacheTable) RemoveAddedItemCallbacks()

RemoveAddedItemCallbacks empties the added item callback queue 【删除添加缓存条目时触发的回调函数】

func (*CacheTable) SetAboutToDeleteItemCallback

func (table *CacheTable) SetAboutToDeleteItemCallback(f func(*CacheItem))

SetAboutToDeleteItemCallback configures a callback, which will be called every time an item is about to be removed from the cache. 【设置删除缓存条目时触发的回调函数】

func (*CacheTable) SetAddedItemCallback

func (table *CacheTable) SetAddedItemCallback(f func(*CacheItem))

SetAddedItemCallback configures a callback, which will be called every time a new item is added to the cache. 【设置添加缓存条目时触发的回调函数】

func (*CacheTable) SetDataLoader

func (table *CacheTable) SetDataLoader(f func(interface{}, ...interface{}) *CacheItem)

SetDataLoader configures a data-loader callback, which will be called when trying to access a non-existing key. The key and 0...n additional arguments are passed to the callback function. 【设置加载一个不存在的key时触发的回调函数】

func (*CacheTable) SetLogger

func (table *CacheTable) SetLogger(logger *log.Logger)

SetLogger sets the logger to be used by this cache table. 【设置日志】

func (*CacheTable) Value

func (table *CacheTable) Value(key interface{}, args ...interface{}) (*CacheItem, error)

Value returns an item from the cache and marks it to be kept alive. You can pass additional arguments to your DataLoader callback function. 【获取value, 会通过KeepAlive更新访问时间和访问次数】

Directories

Path Synopsis
examples
callbacks command
dataloader command
mycachedapp command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL