cache

package
v0.13.2 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2024 License: GPL-3.0, Apache-2.0 Imports: 17 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

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 (
	// Timer for how often to recycle the expired cache items in memory (in seconds)
	DefaultEvery = 60 // 1 minute
)

Functions

func FileGetContents

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

FileGetContents Reads bytes from a file. if non-existent, create this file.

func FilePutContents

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

FilePutContents puts bytes into a file. if non-existent, create this file.

func GetBool

func GetBool(v interface{}) bool

GetBool converts interface to bool.

func GetFloat64

func GetFloat64(v interface{}) float64

GetFloat64 converts interface to float64.

func GetInt

func GetInt(v interface{}) int

GetInt converts interface to int.

func GetInt64

func GetInt64(v interface{}) int64

GetInt64 converts interface to int64.

func GetString

func GetString(v interface{}) string

GetString converts interface to string.

func GobDecode

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

GobDecode Gob decodes a file cache item.

func GobEncode

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

GobEncode Gob encodes a 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 a cached value by key.
	Get(ctx context.Context, key string) (interface{}, error)
	// GetMulti is a batch version of Get.
	GetMulti(ctx context.Context, keys []string) ([]interface{}, error)
	// Set a cached value with key and expire time.
	Put(ctx context.Context, key string, val interface{}, timeout time.Duration) error
	// Delete cached value by key.
	Delete(ctx context.Context, key string) error
	// Increment a cached int value by key, as a counter.
	Incr(ctx context.Context, key string) error
	// Decrement a cached int value by key, as a counter.
	Decr(ctx context.Context, key string) error
	// Check if a cached value exists or not.
	IsExist(ctx context.Context, key string) (bool, error)
	// Clear all cache.
	ClearAll(ctx context.Context) 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 creates a new cache driver by adapter name and config string. config: must be in JSON format such as {"interval":360}. Starts gc automatically.

func NewFileCache

func NewFileCache() Cache

NewFileCache creates a new file cache with no config. The level and expiry need to be set in the 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(context.Context) error

ClearAll cleans cached files (not implemented)

func (*FileCache) Decr

func (fc *FileCache) Decr(ctx context.Context, key string) error

Decr decreases cached int value.

func (*FileCache) Delete

func (fc *FileCache) Delete(ctx context.Context, key string) error

Delete file cache value.

func (*FileCache) Get

func (fc *FileCache) Get(ctx context.Context, key string) (interface{}, error)

Get value from file cache. if nonexistent or expired return an empty string.

func (*FileCache) GetMulti

func (fc *FileCache) GetMulti(ctx context.Context, keys []string) ([]interface{}, error)

GetMulti gets values from file cache. if nonexistent or expired return an empty string.

func (*FileCache) Incr

func (fc *FileCache) Incr(ctx context.Context, key string) error

Incr increases cached int value. fc value is saved forever unless deleted.

func (*FileCache) Init

func (fc *FileCache) Init()

Init makes new a dir for file cache if it does not already exist

func (*FileCache) IsExist

func (fc *FileCache) IsExist(ctx context.Context, key string) (bool, error)

IsExist checks if value exists.

func (*FileCache) Put

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

Put value into file cache. timeout: how long this file should be kept in ms if timeout equals fc.EmbedExpiry(default is 0), cache this item forever.

func (*FileCache) StartAndGC

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

StartAndGC starts gc for file cache. config must be in the format {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 which contains data and expire time.

type Instance

type Instance func() Cache

Instance is a function create a new Cache Instance

type MemoryCache

type MemoryCache struct {
	sync.RWMutex

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

MemoryCache is a memory cache adapter. Contains a RW locker for safe map storage.

func (*MemoryCache) ClearAll

func (bc *MemoryCache) ClearAll(context.Context) error

ClearAll deletes all cache in memory.

func (*MemoryCache) Decr

func (bc *MemoryCache) Decr(ctx context.Context, key string) error

Decr decreases counter in memory.

func (*MemoryCache) Delete

func (bc *MemoryCache) Delete(ctx context.Context, key string) error

Delete cache in memory.

func (*MemoryCache) Get

func (bc *MemoryCache) Get(ctx context.Context, key string) (interface{}, error)

Get returns cache from memory. If non-existent or expired, return nil.

func (*MemoryCache) GetMulti

func (bc *MemoryCache) GetMulti(ctx context.Context, keys []string) ([]interface{}, error)

GetMulti gets caches from memory. If non-existent or expired, return nil.

func (*MemoryCache) Incr

func (bc *MemoryCache) Incr(ctx context.Context, key string) error

Incr increases cache counter in memory. Supports int,int32,int64,uint,uint32,uint64.

func (*MemoryCache) IsExist

func (bc *MemoryCache) IsExist(ctx context.Context, key string) (bool, error)

IsExist checks if cache exists in memory.

func (*MemoryCache) Put

func (bc *MemoryCache) Put(ctx context.Context, key string, val interface{}, timeout time.Duration) error

Put puts cache into memory. If lifespan is 0, it will never overwrite this value unless restarted

func (*MemoryCache) StartAndGC

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

StartAndGC starts memory cache. Checks expiration in every clock time.

type MemoryItem

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

MemoryItem stores memory cache item.

Jump to

Keyboard shortcuts

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