cache

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2022 License: MIT Imports: 13 Imported by: 9

README

Cache

GitHub go.mod Go version GoDoc Go Report Card Actions Status

中文说明

Generic cache use and cache manager for golang.

Provide a unified usage API by packaging various commonly used drivers.

All cache driver implemented the cache.Cache interface. So, You can add any custom driver.

Packaged Drivers:

Internal:

Notice: The built-in implementation is relatively simple and is not recommended for production environments; the production environment recommends using the third-party drivers listed above.

GoDoc

Install

The package supports 3 last Go versions and requires a Go version with modules support.

go get github.com/gookit/cache

Cache Interface

All cache driver implemented the cache.Cache interface. So, You can add any custom driver.

type Cache interface {
	// basic operation
	Has(key string) bool
	Get(key string) interface{}
	Set(key string, val interface{}, ttl time.Duration) (err error)
	Del(key string) error
	// multi operation
	GetMulti(keys []string) map[string]interface{}
	SetMulti(values map[string]interface{}, ttl time.Duration) (err error)
	DelMulti(keys []string) error
	// clear and close
	Clear() error
	Close() error
}

Usage

package main

import (
	"fmt"

	"github.com/gookit/cache"
	"github.com/gookit/cache/gcache"
	"github.com/gookit/cache/gocache"
	"github.com/gookit/cache/goredis"
	"github.com/gookit/cache/redis"
)

func main() {
	// register one(or some) cache driver
	cache.Register(cache.DvrFile, cache.NewFileCache(""))
	// cache.Register(cache.DvrMemory, cache.NewMemoryCache())
	cache.Register(gcache.Name, gcache.New(1000))
	cache.Register(gocache.Name, gocache.NewGoCache(cache.OneDay, cache.FiveMinutes))
	cache.Register(redis.Name, redis.Connect("127.0.0.1:6379", "", 0))
	cache.Register(goredis.Name, goredis.Connect("127.0.0.1:6379", "", 0))

	// setting default driver name
	cache.DefaultUse(gocache.Name)

	// quick use.(it is default driver)
	//
	// set
	cache.Set("name", "cache value", cache.TwoMinutes)
	// get
	val := cache.Get("name")
	// del
	cache.Del("name")

	// get: "cache value"
	fmt.Print(val)

	// More ...
	// fc := cache.Driver(gcache.Name)
	// fc.Set("key", "value", 10)
	// fc.Get("key")
}

With Options

gords := goredis.Connect("127.0.0.1:6379", "", 0)
gords.WithOptions(cache.WithPrefix("cache_"), cache.WithEncode(true))

cache.Register(goredis.Name, gords)

// set
// real key is: "cache_name"
cache.Set("name", "cache value", cache.TwoMinutes)

// get: "cache value"
val := cache.Get("name")

Gookit packages

  • gookit/ini Go config management, use INI files
  • gookit/rux Simple and fast request router for golang HTTP
  • gookit/gcli build CLI application, tool library, running CLI commands
  • gookit/slog Lightweight, extensible, configurable logging library written in Go
  • gookit/event Lightweight event manager and dispatcher implements by Go
  • gookit/cache Provide a unified usage API by packaging various commonly used drivers.
  • gookit/config Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
  • gookit/color A command-line color library with true color support, universal API methods and Windows support
  • gookit/filter Provide filtering, sanitizing, and conversion of golang data
  • gookit/validate Use for data validation and filtering. support Map, Struct, Form data
  • gookit/goutil Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
  • More, please see https://github.com/gookit

License

MIT

Documentation

Overview

Package cache is a generic cache use and cache manager for golang. FileCache is a simple local file system cache implement. MemoryCache is a simple memory cache implement.

Example
package main

import (
	"fmt"

	"github.com/gookit/cache"
	"github.com/gookit/cache/goredis"
	"github.com/gookit/cache/redis"
)

func main() {
	// register some cache driver
	cache.Register(cache.DvrFile, cache.NewFileCache(""))
	cache.Register(cache.DvrMemory, cache.NewMemoryCache())
	cache.Register(redis.Name, redis.Connect("127.0.0.1:6379", "", 0))
	cache.Register(goredis.Name, goredis.Connect("127.0.0.1:6379", "", 0))

	// setting default driver name
	cache.DefaultUse(goredis.Name)

	// quick use.(it is default driver)
	//
	// set
	_ = cache.Set("name", "cache value", cache.TwoMinutes)
	// get
	val := cache.Get("name")
	// del
	_ = cache.Del("name")

	// get: "cache value"
	fmt.Print(val)

	// More ...
	// fc := cache.GetCache(DvrFile)
	// fc.Set("key", "value", 10)
	// fc.Get("key")
}
Output:

Example (WithOptions)
package main

import (
	"github.com/gookit/cache"
	"github.com/gookit/cache/goredis"
	"github.com/gookit/goutil/dump"
)

func main() {
	gords := goredis.Connect("127.0.0.1:6379", "", 0)
	gords.WithOptions(cache.WithPrefix("cache_"), cache.WithEncode(true))

	// register
	cache.Register(goredis.Name, gords)

	// set
	// real key is: "cache_name"
	cache.Set("name", "cache value", cache.TwoMinutes)

	// get: "cache value"
	val := cache.Get("name")

	dump.P(val)
}
Output:

Index

Examples

Constants

View Source
const (
	// Forever Always exist
	Forever = 0

	// Seconds1 1 second
	Seconds1 = time.Second
	// Seconds2 2 second
	Seconds2 = 2 * time.Second
	// Seconds3 3 second
	Seconds3 = 3 * time.Second
	// Seconds5 5 second
	Seconds5 = 5 * time.Second
	// Seconds6 6 second
	Seconds6 = 6 * time.Second
	// Seconds7 7 second
	Seconds7 = 7 * time.Second
	// Seconds8 8 second
	Seconds8 = 8 * time.Second
	// Seconds9 9 second
	Seconds9 = 9 * time.Second
	// Seconds10 10 second
	Seconds10 = 10 * time.Second
	// Seconds15 15 second
	Seconds15 = 15 * time.Second
	// Seconds20 20 second
	Seconds20 = 20 * time.Second
	// Seconds30 30 second
	Seconds30 = 30 * time.Second

	// OneMinutes 1 minutes
	OneMinutes = 60 * time.Second
	// TwoMinutes 2 minutes
	TwoMinutes = 120 * time.Second
	// ThreeMinutes 3 minutes
	ThreeMinutes = 180 * time.Second
	// FiveMinutes 5 minutes
	FiveMinutes = 300 * time.Second
	// TenMinutes 10 minutes
	TenMinutes = 600 * time.Second
	// FifteenMinutes 15 minutes
	FifteenMinutes = 900 * time.Second
	// HalfHour half an hour
	HalfHour = 1800 * time.Second
	// OneHour 1 hour
	OneHour = 3600 * time.Second
	// TwoHour 2 hours
	TwoHour = 7200 * time.Second
	// ThreeHour 3 hours
	ThreeHour = 10800 * time.Second
	// HalfDay 12 hours(half of the day)
	HalfDay = 43200 * time.Second
	// OneDay 24 hours(1 day)
	OneDay = 86400 * time.Second
	// TwoDay 2 day
	TwoDay = 172800 * time.Second
	// ThreeDay 3 day
	ThreeDay = 259200 * time.Second
	// OneWeek 7 day(one week)
	OneWeek = 604800 * time.Second
)

some generic expire time define.

View Source
const (
	DvrFile      = "file"
	DvrRedis     = "redis"
	DvrMemory    = "memory"
	DvrMemCached = "memCached"
	DvrBoltDB    = "boltDB"
	DvrBuntDB    = "buntDB"
)

default supported cache driver name

Variables

data (Un)marshal func

Functions

func BindStruct

func BindStruct(val interface{}, ptr interface{}) error

BindStruct get cache value and map to a struct

func Clear

func Clear() error

Clear all caches

func ClearAll added in v0.2.0

func ClearAll() error

ClearAll all drivers caches

func Close added in v0.2.0

func Close() error

Close all drivers

func DefaultUse added in v0.1.1

func DefaultUse(driverName string)

DefaultUse set default driver name

func Del

func Del(key string) error

Del value by key

func DelMulti

func DelMulti(keys []string) error

DelMulti values by keys

func Get

func Get(key string) interface{}

Get value by key

func GetMulti

func GetMulti(keys []string) map[string]interface{}

GetMulti values by keys

func GobDecode

func GobDecode(bts []byte, ptr interface{}) error

GobDecode decode data by gob.Decode

func GobEncode

func GobEncode(val interface{}) (bs []byte, err error)

GobEncode encode data by gob.Encode

func Has

func Has(key string) bool

Has cache key

func Set

func Set(key string, val interface{}, ttl time.Duration) error

Set value by key

func SetDefName

func SetDefName(driverName string)

SetDefName set default driver name. Deprecated

please use DefaultUse() instead it

func SetMulti

func SetMulti(mv map[string]interface{}, ttl time.Duration) error

SetMulti values

func Unregister added in v0.2.0

func Unregister(name string) int

Unregister an cache driver

func UnregisterAll added in v0.2.0

func UnregisterAll(fn ...func(cache Cache)) int

UnregisterAll cache drivers

func WithDebug added in v0.2.0

func WithDebug(debug bool) func(opt *Option)

WithDebug add option: debug

func WithEncode added in v0.2.0

func WithEncode(encode bool) func(opt *Option)

WithEncode add option: encode

func WithPrefix added in v0.2.0

func WithPrefix(prefix string) func(opt *Option)

WithPrefix add option: prefix

Types

type BaseDriver added in v0.2.0

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

BaseDriver struct

func (*BaseDriver) BuildKeys added in v0.2.0

func (l *BaseDriver) BuildKeys(keys []string) []string

BuildKeys real cache keys build

func (*BaseDriver) Debugf added in v0.2.0

func (l *BaseDriver) Debugf(format string, v ...interface{})

Debugf print an debug message

func (*BaseDriver) IsDebug added in v0.2.0

func (l *BaseDriver) IsDebug() bool

IsDebug get

func (*BaseDriver) Key added in v0.2.0

func (l *BaseDriver) Key(key string) string

Key real cache key build

func (*BaseDriver) LastErr added in v0.2.0

func (l *BaseDriver) LastErr(key string) error

LastErr get

func (*BaseDriver) Logf added in v0.2.0

func (l *BaseDriver) Logf(format string, v ...interface{})

Logf print an log message

func (*BaseDriver) Marshal added in v0.2.0

func (l *BaseDriver) Marshal(val interface{}) (interface{}, error)

Marshal cache value

func (*BaseDriver) MustMarshal added in v0.2.0

func (l *BaseDriver) MustMarshal(val interface{}) ([]byte, error)

MustMarshal cache value

func (*BaseDriver) SetLastErr added in v0.2.0

func (l *BaseDriver) SetLastErr(err error)

SetLastErr save last error

func (*BaseDriver) Unmarshal added in v0.2.0

func (l *BaseDriver) Unmarshal(val []byte, err error) interface{}

Unmarshal cache value

func (*BaseDriver) UnmarshalTo added in v0.2.0

func (l *BaseDriver) UnmarshalTo(bts []byte, ptr interface{}) error

UnmarshalTo cache value

func (*BaseDriver) WithOptions added in v0.2.0

func (l *BaseDriver) WithOptions(optFns ...func(option *Option))

WithOptions for driver

type Cache

type Cache = gsr.SimpleCacher

Cache interface definition

func Default

func Default() Cache

Default get default cache driver instance

func Driver added in v0.1.2

func Driver(driverName string) Cache

Driver get a driver instance by name

func GetCache added in v0.1.1

func GetCache(driverName string) Cache

GetCache returns a driver instance by name. alias of Driver()

func Use

func Use(driverName string) Cache

Use driver object by name and set it as default driver.

type FileCache

type FileCache struct {
	BaseDriver
	// caches in memory
	MemoryCache

	// DisableMemCache disable cache in memory
	DisableMemCache bool
	// contains filtered or unexported fields
}

FileCache definition.

Example
package main

import (
	"fmt"

	"github.com/gookit/cache"
)

func main() {
	c := cache.NewFileCache("./testdata")
	key := "name"

	// set
	c.Set(key, "cache value", cache.TwoMinutes)
	fmt.Println(c.Has(key))

	// get
	val := c.Get(key)
	fmt.Println(val)

	// del
	c.Del(key)
	fmt.Println(c.Has(key))

}
Output:

true
cache value
false

func NewFileCache

func NewFileCache(dir string, pfxAndKey ...string) *FileCache

NewFileCache create a FileCache instance

func (*FileCache) Clear

func (c *FileCache) Clear() error

Clear caches and files

func (*FileCache) Close added in v0.1.1

func (c *FileCache) Close() error

Close cache

func (*FileCache) Del

func (c *FileCache) Del(key string) error

Del value by key

func (*FileCache) DelMulti

func (c *FileCache) DelMulti(keys []string) error

DelMulti values by multi key

func (*FileCache) Get

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

Get value by key

func (*FileCache) GetFilename

func (c *FileCache) GetFilename(key string) string

GetFilename cache file name build

func (*FileCache) GetMulti

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

GetMulti values by multi key

func (*FileCache) Has

func (c *FileCache) Has(key string) bool

Has cache key. will check expire time

func (*FileCache) Set

func (c *FileCache) Set(key string, val interface{}, ttl time.Duration) (err error)

Set value by key

func (*FileCache) SetMulti

func (c *FileCache) SetMulti(values map[string]interface{}, ttl time.Duration) (err error)

SetMulti values by multi key

type Item

type Item struct {
	// Exp expire time
	Exp int64
	// Val cache value storage
	Val interface{}
}

Item for memory cache

func (Item) Expired added in v0.2.0

func (item Item) Expired() bool

Expired check whether expired

type Manager

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

Manager definition

func DefManager added in v0.1.1

func DefManager() *Manager

DefManager get default cache manager instance

func NewManager

func NewManager() *Manager

NewManager create a cache manager instance

func Register

func Register(name string, driver Cache) *Manager

Register driver to manager instance

func Std added in v0.2.0

func Std() *Manager

Std get default cache manager instance

func (*Manager) Cache added in v0.1.2

func (m *Manager) Cache(driverName string) Cache

Cache get driver by name. alias of Driver()

func (*Manager) ClearAll added in v0.2.0

func (m *Manager) ClearAll() (err error)

ClearAll all drivers caches

func (*Manager) Close added in v0.2.0

func (m *Manager) Close() (err error)

Close all drivers

func (*Manager) DefName

func (m *Manager) DefName() string

DefName get default driver name

func (*Manager) Default

func (m *Manager) Default() Cache

Default returns the default driver instance

func (*Manager) DefaultUse added in v0.1.1

func (m *Manager) DefaultUse(driverName string)

DefaultUse set default driver name

func (*Manager) Del added in v0.1.1

func (m *Manager) Del(key string) error

Del value by key

func (*Manager) DelMulti added in v0.1.1

func (m *Manager) DelMulti(keys []string) error

DelMulti values by keys

func (*Manager) Driver

func (m *Manager) Driver(driverName string) Cache

Driver get a driver instance by name

func (*Manager) Get

func (m *Manager) Get(key string) interface{}

Get value by key

func (*Manager) GetMulti added in v0.1.1

func (m *Manager) GetMulti(keys []string) map[string]interface{}

GetMulti values by keys

func (*Manager) Has added in v0.1.1

func (m *Manager) Has(key string) bool

Has cache key

func (*Manager) Register

func (m *Manager) Register(name string, driver Cache) *Manager

Register new cache driver

func (*Manager) Set added in v0.1.1

func (m *Manager) Set(key string, val interface{}, ttl time.Duration) error

Set value by key

func (*Manager) SetDefName

func (m *Manager) SetDefName(driverName string)

SetDefName set default driver name. alias of DefaultUse() Deprecated

please use DefaultUse() instead it

func (*Manager) SetMulti added in v0.1.1

func (m *Manager) SetMulti(mv map[string]interface{}, ttl time.Duration) error

SetMulti values

func (*Manager) Unregister added in v0.2.0

func (m *Manager) Unregister(name string) int

Unregister an cache driver

func (*Manager) UnregisterAll added in v0.2.0

func (m *Manager) UnregisterAll(fn ...func(cache Cache)) int

UnregisterAll cache drivers

func (*Manager) Use

func (m *Manager) Use(driverName string) Cache

Use driver object by name and set it as default driver.

type MarshalFunc

type MarshalFunc func(v interface{}) ([]byte, error)

MarshalFunc define

type MemoryCache

type MemoryCache struct {

	// CacheSize TODO set max cache size
	CacheSize int
	// contains filtered or unexported fields
}

MemoryCache definition.

Example
package main

import (
	"fmt"

	"github.com/gookit/cache"
)

func main() {
	c := cache.NewMemoryCache()
	key := "name"

	// set
	c.Set(key, "cache value", cache.TwoMinutes)
	fmt.Println(c.Has(key), c.Count())

	// get
	val := c.Get(key)
	fmt.Println(val)

	// del
	c.Del(key)
	fmt.Println(c.Has(key), c.Count())

}
Output:

true 1
cache value
false 0

func NewMemoryCache

func NewMemoryCache() *MemoryCache

NewMemoryCache create a memory cache instance

func (*MemoryCache) Clear

func (c *MemoryCache) Clear() error

Clear all caches

func (*MemoryCache) Close added in v0.1.1

func (c *MemoryCache) Close() error

Close cache

func (*MemoryCache) Count

func (c *MemoryCache) Count() int

Count cache item number

func (*MemoryCache) Del

func (c *MemoryCache) Del(key string) error

Del cache by key

func (*MemoryCache) DelMulti

func (c *MemoryCache) DelMulti(keys []string) error

DelMulti values by multi key

func (*MemoryCache) DumpDB

func (c *MemoryCache) DumpDB(file string) error

DumpDB to a file

func (*MemoryCache) Get

func (c *MemoryCache) Get(key string) interface{}

Get cache value by key

func (*MemoryCache) GetMulti

func (c *MemoryCache) GetMulti(keys []string) map[string]interface{}

GetMulti values by multi key

func (*MemoryCache) Has

func (c *MemoryCache) Has(key string) bool

Has cache key

func (*MemoryCache) Iter

func (c *MemoryCache) Iter(file string) error

Iter iteration all caches

func (*MemoryCache) Restore

func (c *MemoryCache) Restore(file string) error

Restore DB from a file

func (*MemoryCache) Set

func (c *MemoryCache) Set(key string, val interface{}, ttl time.Duration) (err error)

Set cache value by key

func (*MemoryCache) SetMulti

func (c *MemoryCache) SetMulti(values map[string]interface{}, ttl time.Duration) (err error)

SetMulti values by multi key

type Option added in v0.2.0

type Option struct {
	Debug bool
	// Encode (Un)marshal save data
	Encode bool
	Logger gsr.Printer
	// Prefix key prefix
	Prefix string
}

Option struct

type UnmarshalFunc

type UnmarshalFunc func(data []byte, v interface{}) error

UnmarshalFunc define

Directories

Path Synopsis
Package badger use the https://github.com/dgraph-io/badger as cache driver
Package badger use the https://github.com/dgraph-io/badger as cache driver
Package bolt use the go.etcd.io/bbolt(github.com/etcd-io/bbolt) as cache driver
Package bolt use the go.etcd.io/bbolt(github.com/etcd-io/bbolt) as cache driver
Package buntdb use the github.com/tidwall/buntdb as cache driver
Package buntdb use the github.com/tidwall/buntdb as cache driver
Package gcache use the github.com/bluele/gcache as cache driver
Package gcache use the github.com/bluele/gcache as cache driver
Package gocache is a memory cache driver implement.
Package gocache is a memory cache driver implement.
Package goredis is a simple redis cache implement.
Package goredis is a simple redis cache implement.
Package leveldb use the https://github.com/syndtr/goleveldb as cache driver
Package leveldb use the https://github.com/syndtr/goleveldb as cache driver
Package memcached use the "github.com/bradfitz/gomemcache/memcache" as cache driver
Package memcached use the "github.com/bradfitz/gomemcache/memcache" as cache driver
Package nutsdb use the https://github.com/xujiajun/nutsdb as cache driver
Package nutsdb use the https://github.com/xujiajun/nutsdb as cache driver
Package redis is a simple redis cache implement.
Package redis is a simple redis cache implement.

Jump to

Keyboard shortcuts

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