cache

package
v0.0.0-...-4ae2e36 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2020 License: MIT, MIT Imports: 11 Imported by: 0

README

go-cache

简介

  1. 支持并发。就是个加了读写锁的map。
  2. 支持key过期。map的value中存了过期时间,启动个定时器遍历map过期删除(遍历的时候加了锁,key太多有性能问题)
  3. 支持key过期事件。key过期会调用一个onEvicted函数,onEvicted是业务方自定义的。
  4. 支持持久化。可以通过 Items()函数取出所有的key:value,然后自己做持久化存储。
  5. 支持初始化加载指定的 key:value 的map
亮点
  • 这里就是 在 cache 上包了一层 Cache,因为cache被runJanitor的goroutine引用,gc会一直忽略对它的回收。
  • 但是包了一层Cache,当外部的使用方不再用Cache的时候,因为没有额外的引用,gc会回收Cache。
  • SetFinalizer会在回收Cache的时候调用stopJanitor,停掉janitor goroutine,从而cache失去引用,也会被gc
type Cache struct {
	*cache
}
func newCacheWithJanitor(de time.Duration, ci time.Duration, m map[string]Item) *Cache {
	c := newCache(de, m)
	C := &Cache{c}
	if ci > 0 {
		runJanitor(c, ci)
		runtime.SetFinalizer(C, stopJanitor) //此函数的意义:当GC准备释放C时,会调用 stopJanitor 方法。
	}
	return C
}

原readme阅读

go-cache is an in-memory key:value store/cache similar to memcached that is suitable for applications running on a single machine. Its major advantage is that, being essentially a thread-safe map[string]interface{} with expiration times, it doesn't need to serialize or transmit its contents over the network.

go-cache 是一个基于内存的key:value储存,它类似于memcached,适用于在一台计算机上运行。它的主要优点是: 它本质上是具有到期时间的线程安全的 map[string]interface ,因此不需要序列化或者在网络上传输内容。

Any object can be stored, for a given duration or forever, and the cache can be safely used by multiple goroutines.

可以储存任何对象(在给定的持续时间内或者永久储存),并且 缓存可以被多个 goroutines 安全的使用

Although go-cache isn't meant to be used as a persistent datastore, the entire cache can be saved to and loaded from a file (using c.Items() to retrieve the items map to serialize, and NewFrom() to create a cache from a deserialized one) to recover from downtime quickly. (See the docs for NewFrom() for caveats.)

尽管不打算将go-cache用作持久数据储存数据库,但是可以将整个缓存保存到文件中,也可以从文件中加载出来。(使用 c.Items 来检索 items map 去 序列化,然后 NewFrom() 来创建一个cache从解序列化的那个。)

Installation 安装

go get github.com/patrickmn/go-cache

Usage 使用
import (
	"fmt"
	"github.com/patrickmn/go-cache"
	"time"
)

func main() {
	// Create a cache with a default expiration time of 5 minutes, and which
	// purges expired items every 10 minutes
	// 创建一个默认过期时间为5分钟的缓存,该缓存每10分钟清除一次过期的item
	c := cache.New(5*time.Minute, 10*time.Minute)

	// Set the value of the key "foo" to "bar", with the default expiration time
	c.Set("foo", "bar", cache.DefaultExpiration)

	// Set the value of the key "baz" to 42, with no expiration time
	// (the item won't be removed until it is re-set, or removed using
	// c.Delete("baz")
	c.Set("baz", 42, cache.NoExpiration)

	// Get the string associated with the key "foo" from the cache
	foo, found := c.Get("foo")
	if found {
		fmt.Println(foo)
	}

	// Since Go is statically typed, and cache values can be anything, type
	// assertion is needed when values are being passed to functions that don't
	// take arbitrary types, (i.e. interface{}). The simplest way to do this for
	// values which will only be used once--e.g. for passing to another
	// function--is:
	//由于Go是静态类型的,并且缓存值可以是任何值,因此当将值传递给不采用任意类型的函数(即interface {})时,需要类型断言。 对于仅使用一次的值执行此操作的最简单方法-例如 传递给另一个
	foo, found := c.Get("foo")
	if found {
		MyFunction(foo.(string))
	}

	// This gets tedious if the value is used several times in the same function.
	// You might do either of the following instead:
	//如果在同一函数中多次使用该值,则将变得很乏味。 您可以执行以下任一操作:
	if x, found := c.Get("foo"); found {
		foo := x.(string)
		// ...
	}
	// or
	var foo string
	if x, found := c.Get("foo"); found {
		foo = x.(string)
	}
	// ...
	// foo can then be passed around freely as a string

	// Want performance? Store pointers!
	c.Set("foo", &MyStruct, cache.DefaultExpiration)
	if x, found := c.Get("foo"); found {
		foo := x.(*MyStruct)
			// ...
	}
}
Reference

godoc or http://godoc.org/github.com/patrickmn/go-cache

Documentation

Index

Constants

View Source
const (
	// For use with functions that take an expiration time.
	NoExpiration time.Duration = -1
	// For use with functions that take an expiration time. Equivalent to
	// passing in the same expiration duration as was given to New() or
	// NewFrom() when the cache was created (e.g. 5 minutes.)
	DefaultExpiration time.Duration = 0
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

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

func New

func New(defaultExpiration, cleanupInterval time.Duration) *Cache

Return a new cache with a given default expiration duration and cleanup interval. If the expiration duration is less than one (or NoExpiration), the items in the cache never expire (by default), and must be deleted manually. If the cleanup interval is less than one, expired items are not deleted from the cache before calling c.DeleteExpired(). 返回一个cache,该cache有默认的过期时间和清理间隔 如果过期时间比1小(获取没有过期时间),那么items 将永不过期(默认情况下),并且必须手动删除。 如果清理间隔小于1,在调用c.DeleteExpired()之前,过期的items不会被删除。

func NewFrom

func NewFrom(defaultExpiration, cleanupInterval time.Duration, items map[string]Item) *Cache

Return a new cache with a given default expiration duration and cleanup interval. If the expiration duration is less than one (or NoExpiration), the items in the cache never expire (by default), and must be deleted manually. If the cleanup interval is less than one, expired items are not deleted from the cache before calling c.DeleteExpired().

NewFrom() also accepts an items map which will serve as the underlying map for the cache. This is useful for starting from a deserialized cache (serialized using e.g. gob.Encode() on c.Items()), or passing in e.g. make(map[string]Item, 500) to improve startup performance when the cache is expected to reach a certain minimum size.

Only the cache's methods synchronize access to this map, so it is not recommended to keep any references to the map around after creating a cache. If need be, the map can be accessed at a later point using c.Items() (subject to the same caveat.)

Note regarding serialization: When using e.g. gob, make sure to gob.Register() the individual types stored in the cache before encoding a map retrieved with c.Items(), and to register those same types before decoding a blob containing an items map.

func (Cache) Add

func (c Cache) Add(k string, x interface{}, d time.Duration) error

Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. Returns an error otherwise. Add 新增一个key:value到cache中,如果key已经在cache存在,将会返回错误。

func (Cache) Decrement

func (c Cache) Decrement(k string, n int64) error

Decrement an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to decrement it by n. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementInt64.

func (Cache) DecrementFloat

func (c Cache) DecrementFloat(k string, n float64) error

Decrement an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to decrement it by n. Pass a negative number to decrement the value. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementFloat64.

func (Cache) DecrementFloat32

func (c Cache) DecrementFloat32(k string, n float32) (float32, error)

Decrement an item of type float32 by n. Returns an error if the item's value is not an float32, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementFloat64

func (c Cache) DecrementFloat64(k string, n float64) (float64, error)

Decrement an item of type float64 by n. Returns an error if the item's value is not an float64, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementInt

func (c Cache) DecrementInt(k string, n int) (int, error)

Decrement an item of type int by n. Returns an error if the item's value is not an int, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementInt16

func (c Cache) DecrementInt16(k string, n int16) (int16, error)

Decrement an item of type int16 by n. Returns an error if the item's value is not an int16, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementInt32

func (c Cache) DecrementInt32(k string, n int32) (int32, error)

Decrement an item of type int32 by n. Returns an error if the item's value is not an int32, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementInt64

func (c Cache) DecrementInt64(k string, n int64) (int64, error)

Decrement an item of type int64 by n. Returns an error if the item's value is not an int64, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementInt8

func (c Cache) DecrementInt8(k string, n int8) (int8, error)

Decrement an item of type int8 by n. Returns an error if the item's value is not an int8, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementUint

func (c Cache) DecrementUint(k string, n uint) (uint, error)

Decrement an item of type uint by n. Returns an error if the item's value is not an uint, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementUint16

func (c Cache) DecrementUint16(k string, n uint16) (uint16, error)

Decrement an item of type uint16 by n. Returns an error if the item's value is not an uint16, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementUint32

func (c Cache) DecrementUint32(k string, n uint32) (uint32, error)

Decrement an item of type uint32 by n. Returns an error if the item's value is not an uint32, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementUint64

func (c Cache) DecrementUint64(k string, n uint64) (uint64, error)

Decrement an item of type uint64 by n. Returns an error if the item's value is not an uint64, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementUint8

func (c Cache) DecrementUint8(k string, n uint8) (uint8, error)

Decrement an item of type uint8 by n. Returns an error if the item's value is not an uint8, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) DecrementUintptr

func (c Cache) DecrementUintptr(k string, n uintptr) (uintptr, error)

Decrement an item of type uintptr by n. Returns an error if the item's value is not an uintptr, or if it was not found. If there is no error, the decremented value is returned.

func (Cache) Delete

func (c Cache) Delete(k string)

Delete an item from the cache. Does nothing if the key is not in the cache. Delete 从cache中删除一个item。 如果key不存在,就啥都不做

func (Cache) DeleteExpired

func (c Cache) DeleteExpired()

Delete all expired items from the cache. 从cache中删除所有过期的items,然后调用删除回调函数。

func (Cache) Flush

func (c Cache) Flush()

Delete all items from the cache. 从缓存中删除所有项目。

func (Cache) Get

func (c Cache) Get(k string) (interface{}, bool)

Get an item from the cache. Returns the item or nil, and a bool indicating whether the key was found. 从 cache 中获取一个 item。 返回一个item或者nil,还有 一个bool代表key是否找到

func (Cache) GetWithExpiration

func (c Cache) GetWithExpiration(k string) (interface{}, time.Time, bool)

GetWithExpiration returns an item and its expiration time from the cache. It returns the item or nil, the expiration time if one is set (if the item never expires a zero value for time.Time is returned), and a bool indicating whether the key was found. GetWithExpiration 返回一个item和它的过期时间 它返回 item 或者nil,过期时间(如果永不过期,就返回0值),和一个bool代表key是否被找到。

func (Cache) Increment

func (c Cache) Increment(k string, n int64) error

Increment an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to increment it by n. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementInt64.

func (Cache) IncrementFloat

func (c Cache) IncrementFloat(k string, n float64) error

Increment an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to increment it by n. Pass a negative number to decrement the value. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementFloat64.

func (Cache) IncrementFloat32

func (c Cache) IncrementFloat32(k string, n float32) (float32, error)

Increment an item of type float32 by n. Returns an error if the item's value is not an float32, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementFloat64

func (c Cache) IncrementFloat64(k string, n float64) (float64, error)

Increment an item of type float64 by n. Returns an error if the item's value is not an float64, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementInt

func (c Cache) IncrementInt(k string, n int) (int, error)

Increment an item of type int by n. Returns an error if the item's value is not an int, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementInt16

func (c Cache) IncrementInt16(k string, n int16) (int16, error)

Increment an item of type int16 by n. Returns an error if the item's value is not an int16, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementInt32

func (c Cache) IncrementInt32(k string, n int32) (int32, error)

Increment an item of type int32 by n. Returns an error if the item's value is not an int32, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementInt64

func (c Cache) IncrementInt64(k string, n int64) (int64, error)

Increment an item of type int64 by n. Returns an error if the item's value is not an int64, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementInt8

func (c Cache) IncrementInt8(k string, n int8) (int8, error)

Increment an item of type int8 by n. Returns an error if the item's value is not an int8, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementUint

func (c Cache) IncrementUint(k string, n uint) (uint, error)

Increment an item of type uint by n. Returns an error if the item's value is not an uint, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementUint16

func (c Cache) IncrementUint16(k string, n uint16) (uint16, error)

Increment an item of type uint16 by n. Returns an error if the item's value is not an uint16, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementUint32

func (c Cache) IncrementUint32(k string, n uint32) (uint32, error)

Increment an item of type uint32 by n. Returns an error if the item's value is not an uint32, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementUint64

func (c Cache) IncrementUint64(k string, n uint64) (uint64, error)

Increment an item of type uint64 by n. Returns an error if the item's value is not an uint64, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementUint8

func (c Cache) IncrementUint8(k string, n uint8) (uint8, error)

Increment an item of type uint8 by n. Returns an error if the item's value is not an uint8, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) IncrementUintptr

func (c Cache) IncrementUintptr(k string, n uintptr) (uintptr, error)

Increment an item of type uintptr by n. Returns an error if the item's value is not an uintptr, or if it was not found. If there is no error, the incremented value is returned.

func (Cache) ItemCount

func (c Cache) ItemCount() int

Returns the number of items in the cache. This may include items that have expired, but have not yet been cleaned up. 返回缓存中的项目数。 这可能包括已过期但尚未清理的项目。

func (Cache) Items

func (c Cache) Items() map[string]Item

Copies all unexpired items in the cache into a new map and returns it. 将缓存中所有未过期的项目复制到新映射中并返回。

func (Cache) Load

func (c Cache) Load(r io.Reader) error

Add (Gob-serialized) cache items from an io.Reader, excluding any items with keys that already exist (and haven't expired) in the current cache. 从io.Reader添加(Gob序列化的)缓存项,但不包括当前缓存中已存在(但尚未过期)键的所有项。 NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (Cache) LoadFile

func (c Cache) LoadFile(fname string) error

Load and add cache items from the given filename, excluding any items with keys that already exist in the current cache.

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (Cache) OnEvicted

func (c Cache) OnEvicted(f func(string, interface{}))

Sets an (optional) function that is called with the key and value when an item is evicted from the cache. (Including when it is deleted manually, but not when it is overwritten.) Set to nil to disable. 设置从缓存中逐出项目时使用键和值调用的(可选)函数。(包括手动删除的时间,但不包括被覆盖的时间。)设置为nil禁用。

func (Cache) Replace

func (c Cache) Replace(k string, x interface{}, d time.Duration) error

Set a new value for the cache key only if it already exists, and the existing item hasn't expired. Returns an error otherwise. 更新一个现有的key:value,如果不存在会返回错误,只更新已有并且未过期的。

func (Cache) Save

func (c Cache) Save(w io.Writer) (err error)

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().) 注意:不推荐使用此方法,而推荐使用c.Items()和NewFrom()(请参阅有关NewFrom()的文档。)

func (Cache) SaveFile

func (c Cache) SaveFile(fname string) error

Save the cache's items to the given filename, creating the file if it doesn't exist, and overwriting it if it does. 将 cache 的 items 保存到 给定的 filename 文件中。 NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (Cache) Set

func (c Cache) Set(k string, x interface{}, d time.Duration)

Add an item to the cache, replacing any existing item. If the duration is 0 (DefaultExpiration), the cache's default expiration time is used. If it is -1 (NoExpiration), the item never expires. 将item 添加到缓存,替换任何现有item 。 如果参数d为0,那么cache的默认expiration time将被使用。 如果参数d=-1(NoExpiration),item将永远不会过期。

func (Cache) SetDefault

func (c Cache) SetDefault(k string, x interface{})

Add an item to the cache, replacing any existing item, using the default expiration. 使用默认时间 set 一个key:value对

type Item

type Item struct {
	Object     interface{}
	Expiration int64
}

func (Item) Expired

func (item Item) Expired() bool

Returns true if the item has expired. 过期返回true

Jump to

Keyboard shortcuts

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