go-cache/cache.go

305 lines
7.5 KiB
Go
Raw Normal View History

2012-01-02 18:01:04 +08:00
package cache
import (
"fmt"
"runtime"
"sync"
"time"
)
type Item struct {
Object ValueType
2015-12-01 04:02:02 +08:00
Expiration int64
2012-01-29 10:16:59 +08:00
}
// Returns true if the item has expired.
func (item Item) Expired() bool {
2015-12-01 04:02:02 +08:00
if item.Expiration == 0 {
2015-12-01 02:50:17 +08:00
return false
}
return time.Now().UnixNano() > item.Expiration
2012-01-29 10:16:59 +08:00
}
const (
// For use with functions that take an expiration time.
2014-12-22 15:48:52 +08:00
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
)
2012-01-02 18:01:04 +08:00
type Cache struct {
*cache
2012-06-22 10:56:12 +08:00
// If this is confusing, see the comment at the bottom of New()
2012-01-02 18:01:04 +08:00
}
type cache struct {
defaultExpiration time.Duration
items map[string]Item
2015-11-28 02:03:24 +08:00
mu sync.RWMutex
onEvicted func(string, *ValueType)
2012-01-02 18:01:04 +08:00
janitor *janitor
}
// 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.
func (c *cache) Set(k string, x ValueType, d time.Duration) {
// "Inlining" of set
var e int64
if d == DefaultExpiration {
d = c.defaultExpiration
}
if d > 0 {
e = time.Now().Add(d).UnixNano()
}
2015-11-28 02:03:24 +08:00
c.mu.Lock()
c.items[k] = Item{
Object: x,
Expiration: e,
}
// TODO: Calls to mu.Unlock are currently not deferred because defer
// adds ~200 ns (as of go1.)
2015-11-28 02:03:24 +08:00
c.mu.Unlock()
2012-01-04 15:54:01 +08:00
}
func (c *cache) set(k string, x ValueType, d time.Duration) {
2015-12-01 04:02:02 +08:00
var e int64
if d == DefaultExpiration {
d = c.defaultExpiration
2012-01-02 18:01:04 +08:00
}
if d > 0 {
2015-12-01 04:02:02 +08:00
e = time.Now().Add(d).UnixNano()
2012-01-02 18:01:04 +08:00
}
c.items[k] = Item{
Object: x,
2012-01-02 18:01:04 +08:00
Expiration: e,
}
}
// 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.
func (c *cache) Add(k string, x ValueType, d time.Duration) error {
2015-11-28 02:03:24 +08:00
c.mu.Lock()
2012-01-04 15:54:01 +08:00
_, found := c.get(k)
2012-01-02 21:04:47 +08:00
if found {
2015-11-28 02:03:24 +08:00
c.mu.Unlock()
return fmt.Errorf("Item %s already exists", k)
2012-01-02 21:04:47 +08:00
}
2012-01-04 15:54:01 +08:00
c.set(k, x, d)
2015-11-28 02:03:24 +08:00
c.mu.Unlock()
2012-01-02 21:04:47 +08:00
return nil
}
// Set a new value for the cache key only if it already exists, and the existing
// item hasn't expired. Returns an error otherwise.
func (c *cache) Replace(k string, x ValueType, d time.Duration) error {
2015-11-28 02:03:24 +08:00
c.mu.Lock()
2012-01-04 15:54:01 +08:00
_, found := c.get(k)
2012-01-02 21:04:47 +08:00
if !found {
2015-11-28 02:03:24 +08:00
c.mu.Unlock()
return fmt.Errorf("Item %s doesn't exist", k)
2012-01-02 21:04:47 +08:00
}
2012-01-04 15:54:01 +08:00
c.set(k, x, d)
2015-11-28 02:03:24 +08:00
c.mu.Unlock()
2012-01-02 21:04:47 +08:00
return nil
}
// Get an item from the cache. Returns the item or nil, and a bool indicating
// whether the key was found.
func (c *cache) Get(k string) *ValueType {
2015-11-28 02:03:24 +08:00
c.mu.RLock()
2015-12-01 04:02:02 +08:00
// "Inlining" of get and Expired
2015-12-01 02:50:17 +08:00
item, found := c.items[k]
2015-12-01 03:47:22 +08:00
if !found {
2015-12-01 02:50:17 +08:00
c.mu.RUnlock()
return nil
2015-12-01 02:50:17 +08:00
}
2015-12-01 04:02:02 +08:00
if item.Expiration > 0 {
if time.Now().UnixNano() > item.Expiration {
2015-12-01 03:47:22 +08:00
c.mu.RUnlock()
return nil
2015-12-01 03:47:22 +08:00
}
}
2015-11-28 02:03:24 +08:00
c.mu.RUnlock()
return &item.Object
2012-01-04 15:54:01 +08:00
}
func (c *cache) get(k string) (*ValueType, bool) {
item, found := c.items[k]
2015-12-01 03:47:22 +08:00
if !found {
2012-01-02 18:01:04 +08:00
return nil, false
}
2015-12-01 03:47:22 +08:00
// "Inlining" of Expired
2015-12-01 04:02:02 +08:00
if item.Expiration > 0 {
if time.Now().UnixNano() > item.Expiration {
2015-12-01 03:47:22 +08:00
return nil, false
}
}
return &item.Object, true
2012-01-02 18:01:04 +08:00
}
2012-06-22 10:56:12 +08:00
// 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
2012-06-22 10:56:12 +08:00
// 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.
// TODO: Increment for numberic type.
func (c *cache) Increment(k string, n int64) error {
return nil
}
2012-06-22 10:56:12 +08:00
// 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.
// TODO: Decrement
2012-01-04 16:11:27 +08:00
func (c *cache) Decrement(k string, n int64) error {
// TODO: Implement Increment and Decrement more cleanly.
// (Cannot do Increment(k, n*-1) for uints.)
return nil
2012-01-02 20:52:43 +08:00
}
// Delete an item from the cache. Does nothing if the key is not in the cache.
2012-01-02 20:52:43 +08:00
func (c *cache) Delete(k string) {
2015-11-28 02:03:24 +08:00
c.mu.Lock()
2015-11-28 11:00:08 +08:00
v, evicted := c.delete(k)
2015-11-28 02:03:24 +08:00
c.mu.Unlock()
2015-11-28 11:00:08 +08:00
if evicted {
c.onEvicted(k, v)
}
2012-01-04 15:54:01 +08:00
}
func (c *cache) delete(k string) (*ValueType, bool) {
2015-11-28 11:00:08 +08:00
if c.onEvicted != nil {
if v, found := c.items[k]; found {
delete(c.items, k)
return &v.Object, true
2015-11-28 11:00:08 +08:00
}
}
delete(c.items, k)
2015-11-28 11:00:08 +08:00
return nil, false
}
type keyAndValue struct {
key string
value *ValueType
2012-01-02 18:01:04 +08:00
}
// Delete all expired items from the cache.
2012-01-02 18:01:04 +08:00
func (c *cache) DeleteExpired() {
var evictedItems []keyAndValue
now := time.Now().UnixNano()
2015-11-28 02:03:24 +08:00
c.mu.Lock()
for k, v := range c.items {
// "Inlining" of expired
2015-12-01 04:02:02 +08:00
if v.Expiration > 0 && now > v.Expiration {
2015-11-28 11:00:08 +08:00
ov, evicted := c.delete(k)
if evicted {
evictedItems = append(evictedItems, keyAndValue{k, ov})
}
2012-01-02 18:01:04 +08:00
}
}
2015-11-28 02:03:24 +08:00
c.mu.Unlock()
2015-11-28 11:00:08 +08:00
for _, v := range evictedItems {
c.onEvicted(v.key, v.value)
}
}
// 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.
func (c *cache) OnEvicted(f func(string, *ValueType)) {
2015-11-28 11:00:08 +08:00
c.mu.Lock()
c.onEvicted = f
2015-12-01 05:18:49 +08:00
c.mu.Unlock()
2012-01-02 18:01:04 +08:00
}
// Returns the number of items in the cache. This may include items that have
// expired, but have not yet been cleaned up. Equivalent to len(c.Items()).
func (c *cache) ItemCount() int {
2015-11-28 02:03:24 +08:00
c.mu.RLock()
n := len(c.items)
2015-11-28 02:03:24 +08:00
c.mu.RUnlock()
return n
}
// Delete all items from the cache.
func (c *cache) Flush() {
2015-11-28 02:03:24 +08:00
c.mu.Lock()
c.items = map[string]Item{}
2015-11-28 02:03:24 +08:00
c.mu.Unlock()
2012-01-02 18:01:04 +08:00
}
2012-01-29 10:16:59 +08:00
type janitor struct {
Interval time.Duration
stop chan bool
2012-01-02 18:01:04 +08:00
}
func (j *janitor) Run(c *cache) {
j.stop = make(chan bool)
ticker := time.NewTicker(j.Interval)
2012-01-02 18:01:04 +08:00
for {
select {
case <-ticker.C:
2012-01-02 18:01:04 +08:00
c.DeleteExpired()
case <-j.stop:
ticker.Stop()
2012-01-02 18:01:04 +08:00
return
}
}
}
func stopJanitor(c *Cache) {
c.janitor.stop <- true
2012-01-02 18:01:04 +08:00
}
func runJanitor(c *cache, ci time.Duration) {
j := &janitor{
Interval: ci,
}
c.janitor = j
go j.Run(c)
2012-01-02 18:01:04 +08:00
}
func newCache(de time.Duration, m map[string]Item) *cache {
2012-01-02 18:01:04 +08:00
if de == 0 {
de = -1
}
c := &cache{
defaultExpiration: de,
items: m,
2012-01-02 18:01:04 +08:00
}
return c
}
func newCacheWithJanitor(de time.Duration, ci time.Duration, m map[string]Item) *Cache {
c := newCache(de, m)
// This trick ensures that the janitor goroutine (which--granted it
// was enabled--is running DeleteExpired on c forever) does not keep
// the returned C object from being garbage collected. When it is
// garbage collected, the finalizer stops the janitor goroutine, after
// which c can be collected.
2012-01-02 18:01:04 +08:00
C := &Cache{c}
if ci > 0 {
runJanitor(c, ci)
// 如果C被回收了,但是c不会,因为stopJanitor是一个一直运行的
// goroutine对c一直有引用不会被回收,所以加一个Finalizer来停掉
// 这个goroutine然后让c被回收.
2012-01-02 18:01:04 +08:00
runtime.SetFinalizer(C, stopJanitor)
}
return C
}
// 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().
func New(defaultExpiration, cleanupInterval time.Duration) *Cache {
items := make(map[string]Item)
return newCacheWithJanitor(defaultExpiration, cleanupInterval, items)
}