cache

package
v0.0.0-...-6e21e7b Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2018 License: Apache-2.0 Imports: 16 Imported by: 0

README

cache

cache is a Go cache manager. It can use many cache adapters. The repo is inspired by database/sql .

How to install?

go get github.com/astaxie/beego/cache

What adapters are supported?

As of now this cache support memory, Memcache and Redis.

How to use it?

First you must import it

import (
	"github.com/astaxie/beego/cache"
)

Then init a Cache (example with memory adapter)

bm, err := cache.NewCache("memory", `{"interval":60}`)	

Use it like this:

bm.Put("astaxie", 1, 10 * time.Second)
bm.Get("astaxie")
bm.IsExist("astaxie")
bm.Delete("astaxie")

Memory adapter

Configure memory adapter like this:

{"interval":60}

interval means the gc time. The cache will check at each time interval, whether item has expired.

Memcache adapter

Memcache adapter use the gomemcache client.

Configure like this:

{"conn":"127.0.0.1:11211"}

Redis adapter

Redis adapter use the redigo client.

Configure like this:

{"conn":":6039"}

Documentation

Overview

Package cache provide a Cache interface and some implement engine Usage:

import(

"github.com/astaxie/beego/cache"

)

bm, err := cache.NewCache("memory", `{"interval":60}`)

Use it like this:

	bm.Put("astaxie", 1, 10 * time.Second)
	bm.Get("astaxie")
	bm.IsExist("astaxie")
	bm.Delete("astaxie")

 more docs http://beego.me/docs/module/cache.md

Package cache implements a LRU cache.

The implementation borrows heavily from SmallLRUCache (originally by Nathan Schrenk). The object maintains a doubly-linked list of elements. When an element is accessed, it is promoted to the head of the list. When space is needed, the element at the tail of the list (the least recently used element) is evicted.

Index

Constants

This section is empty.

Variables

View Source
var (
	FileCachePath           = "cache"     // cache directory
	FileCacheFileSuffix     = ".bin"      // cache file suffix
	FileCacheDirectoryLevel = 2           // cache file deep level if auto generated cache files.
	FileCacheEmbedExpiry    time.Duration // cache expire time, default is no expire forever.
)

FileCache Config

View Source
var (
	// DefaultEvery means the clock time of recycling the expired cache items in memory.
	DefaultEvery = 60 // 1 minute
)

Functions

func FileGetContents

func FileGetContents(filename string) (data []byte, e error)

FileGetContents Get bytes to file. if non-exist, create this file.

func FilePutContents

func FilePutContents(filename string, content []byte) error

FilePutContents Put bytes to file. if non-exist, create this file.

func GetBool

func GetBool(v interface{}) bool

GetBool convert interface to bool.

func GetFloat64

func GetFloat64(v interface{}) float64

GetFloat64 convert interface to float64.

func GetInt

func GetInt(v interface{}) int

GetInt convert interface to int.

func GetInt64

func GetInt64(v interface{}) int64

GetInt64 convert interface to int64.

func GetString

func GetString(v interface{}) string

GetString convert interface to string.

func GobDecode

func GobDecode(data []byte, to *FileCacheItem) error

GobDecode Gob decodes file cache item.

func GobEncode

func GobEncode(data interface{}) ([]byte, error)

GobEncode Gob encodes file cache item.

func Register

func Register(name string, adapter Instance)

Register makes a cache adapter available by the adapter name. If Register is called twice with the same name or if driver is nil, it panics.

Types

type Cache

type Cache interface {
	// get cached value by key.
	Get(key string) interface{}
	// GetMulti is a batch version of Get.
	GetMulti(keys []string) []interface{}
	// set cached value with key and expire time.
	Put(key string, val interface{}, timeout time.Duration) error
	// delete cached value by key.
	Delete(key string) error
	// increase cached int value by key, as a counter.
	Incr(key string) error
	// decrease cached int value by key, as a counter.
	Decr(key string) error
	// check if cached value exists or not.
	IsExist(key string) bool
	// clear all cache.
	ClearAll() error
	// start gc routine based on config string settings.
	StartAndGC(config string) error
}

Cache interface contains all behaviors for cache adapter. usage:

cache.Register("file",cache.NewFileCache) // this operation is run in init method of file.go.
c,err := cache.NewCache("file","{....}")
c.Put("key",value, 3600 * time.Second)
v := c.Get("key")

c.Incr("counter")  // now is 1
c.Incr("counter")  // now is 2
count := c.Get("counter").(int)

func NewCache

func NewCache(adapterName, config string) (adapter Cache, err error)

NewCache Create a new cache driver by adapter name and config string. config need to be correct JSON as string: {"interval":360}. it will start gc automatically.

func NewFileCache

func NewFileCache() Cache

NewFileCache Create new file cache with no config. the level and expiry need set in method StartAndGC as config string.

func NewMemoryCache

func NewMemoryCache() Cache

NewMemoryCache returns a new MemoryCache.

type FileCache

type FileCache struct {
	CachePath      string
	FileSuffix     string
	DirectoryLevel int
	EmbedExpiry    int
}

FileCache is cache adapter for file storage.

func (*FileCache) ClearAll

func (fc *FileCache) ClearAll() error

ClearAll will clean cached files. not implemented.

func (*FileCache) Decr

func (fc *FileCache) Decr(key string) error

Decr will decrease cached int value.

func (*FileCache) Delete

func (fc *FileCache) Delete(key string) error

Delete file cache value.

func (*FileCache) Get

func (fc *FileCache) Get(key string) interface{}

Get value from file cache. if non-exist or expired, return empty string.

func (*FileCache) GetMulti

func (fc *FileCache) GetMulti(keys []string) []interface{}

GetMulti gets values from file cache. if non-exist or expired, return empty string.

func (*FileCache) Incr

func (fc *FileCache) Incr(key string) error

Incr will increase cached int value. fc value is saving forever unless Delete.

func (*FileCache) Init

func (fc *FileCache) Init()

Init will make new dir for file cache if not exist.

func (*FileCache) IsExist

func (fc *FileCache) IsExist(key string) bool

IsExist check value is exist.

func (*FileCache) Put

func (fc *FileCache) Put(key string, val interface{}, timeout time.Duration) error

Put value into file cache. timeout means how long to keep this file, unit of ms. if timeout equals FileCacheEmbedExpiry(default is 0), cache this item forever.

func (*FileCache) StartAndGC

func (fc *FileCache) StartAndGC(config string) error

StartAndGC will start and begin gc for file cache. the config need to be like {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":2,"EmbedExpiry":0}

type FileCacheItem

type FileCacheItem struct {
	Data       interface{}
	Lastaccess time.Time
	Expired    time.Time
}

FileCacheItem is basic unit of file cache adapter. it contains data and expire time.

type Instance

type Instance func() Cache

Instance is a function create a new Cache Instance

type Item

type Item struct {
	Key   string
	Value Value
}

Item is what is stored in the cache

type LRUCache

type LRUCache struct {
	// contains filtered or unexported fields
}

LRUCache is a typical LRU cache implementation. If the cache reaches the capacity, the least recently used item is deleted from the cache. Note the capacity is not the number of items, but the total sum of the Size() of each item.

func NewLRUCache

func NewLRUCache(capacity int64) *LRUCache

NewLRUCache creates a new empty cache with the given capacity.

func (*LRUCache) Capacity

func (lru *LRUCache) Capacity() int64

Capacity returns the cache maximum capacity.

func (*LRUCache) Clear

func (lru *LRUCache) Clear()

Clear will clear the entire cache.

func (*LRUCache) Delete

func (lru *LRUCache) Delete(key string) bool

Delete removes an entry from the cache, and returns if the entry existed.

func (*LRUCache) Evictions

func (lru *LRUCache) Evictions() int64

Evictions returns the eviction count.

func (*LRUCache) Get

func (lru *LRUCache) Get(key string) (v Value, ok bool)

Get returns a value from the cache, and marks the entry as most recently used.

func (*LRUCache) Items

func (lru *LRUCache) Items() []Item

Items returns all the values for the cache, ordered from most recently used to last recently used.

func (*LRUCache) Keys

func (lru *LRUCache) Keys() []string

Keys returns all the keys for the cache, ordered from most recently used to last recently used.

func (*LRUCache) Length

func (lru *LRUCache) Length() int64

Length returns how many elements are in the cache

func (*LRUCache) Oldest

func (lru *LRUCache) Oldest() (oldest time.Time)

Oldest returns the insertion time of the oldest element in the cache, or a IsZero() time if cache is empty.

func (*LRUCache) Peek

func (lru *LRUCache) Peek(key string) (v Value, ok bool)

Peek returns a value from the cache without changing the LRU order.

func (*LRUCache) Set

func (lru *LRUCache) Set(key string, value Value)

Set sets a value in the cache.

func (*LRUCache) SetCapacity

func (lru *LRUCache) SetCapacity(capacity int64)

SetCapacity will set the capacity of the cache. If the capacity is smaller, and the current cache size exceed that capacity, the cache will be shrank.

func (*LRUCache) SetIfAbsent

func (lru *LRUCache) SetIfAbsent(key string, value Value)

SetIfAbsent will set the value in the cache if not present. If the value exists in the cache, we don't set it.

func (*LRUCache) Size

func (lru *LRUCache) Size() int64

Size returns the sum of the objects' Size() method.

func (*LRUCache) Stats

func (lru *LRUCache) Stats() (length, size, capacity, evictions int64, oldest time.Time)

Stats returns a few stats on the cache.

func (*LRUCache) StatsJSON

func (lru *LRUCache) StatsJSON() string

StatsJSON returns stats as a JSON object in a string.

type MemoryCache

type MemoryCache struct {
	sync.RWMutex

	Every int // run an expiration check Every clock time
	// contains filtered or unexported fields
}

MemoryCache is Memory cache adapter. it contains a RW locker for safe map storage.

func (*MemoryCache) ClearAll

func (bc *MemoryCache) ClearAll() error

ClearAll will delete all cache in memory.

func (*MemoryCache) Decr

func (bc *MemoryCache) Decr(key string) error

Decr decrease counter in memory.

func (*MemoryCache) Delete

func (bc *MemoryCache) Delete(name string) error

Delete cache in memory.

func (*MemoryCache) Get

func (bc *MemoryCache) Get(name string) interface{}

Get cache from memory. if non-existed or expired, return nil.

func (*MemoryCache) GetMulti

func (bc *MemoryCache) GetMulti(names []string) []interface{}

GetMulti gets caches from memory. if non-existed or expired, return nil.

func (*MemoryCache) Incr

func (bc *MemoryCache) Incr(key string) error

Incr increase cache counter in memory. it supports int,int32,int64,uint,uint32,uint64.

func (*MemoryCache) IsExist

func (bc *MemoryCache) IsExist(name string) bool

IsExist check cache exist in memory.

func (*MemoryCache) Put

func (bc *MemoryCache) Put(name string, value interface{}, lifespan time.Duration) error

Put cache to memory. if lifespan is 0, it will be forever till restart.

func (*MemoryCache) StartAndGC

func (bc *MemoryCache) StartAndGC(config string) error

StartAndGC start memory cache. it will check expiration in every clock time.

type MemoryItem

type MemoryItem struct {
	// contains filtered or unexported fields
}

MemoryItem store memory cache item.

type Value

type Value interface {
	// Size returns how big this value is. If you want to just track
	// the cache by number of objects, you may return the size as 1.
	Size() int
}

Value is the interface values that go into LRUCache need to satisfy

Directories

Path Synopsis
Package redis for cache provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/astaxie/beego/cache/redis" "github.com/astaxie/beego/cache" ) bm, err := cache.NewCache("redis", `{"conn":"127.0.0.1:11211"}`) more docs http://beego.me/docs/module/cache.md
Package redis for cache provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/astaxie/beego/cache/redis" "github.com/astaxie/beego/cache" ) bm, err := cache.NewCache("redis", `{"conn":"127.0.0.1:11211"}`) more docs http://beego.me/docs/module/cache.md

Jump to

Keyboard shortcuts

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