cache

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2024 License: MIT Imports: 3 Imported by: 16

README

go-cache

CI GoDoc

中文文档

image

Provides a memory-based cache package for Gopher.

Install

go get -u github.com/fanjindong/go-cache

Fast Start

import "github.com/fanjindong/go-cache"

func main() {
    c := cache.NewMemCache()
    c.Set("a", 1)
    c.Set("b", 1, cache.WithEx(1*time.Second))
    time.sleep(1*time.Second)
    c.Get("a") // 1, true
    c.Get("b") // nil, false
}

Performance Benchmark

In the concurrent scenario, it has three times the performance improvement compared to github.com/patrickmn/go-cache.

benchmark

BenchmarkGoCacheConcurrentSetWithEx-8            	 3040422	       371 ns/op
BenchmarkPatrickmnGoCacheConcurrentSetWithEx-8   	 1000000	      1214 ns/op
BenchmarkGoCacheConcurrentSet-8                  	 2634070	       440 ns/op
BenchmarkPatrickmnGoCacheConcurrentSet-8         	 1000000	      1204 ns/op

Advanced

Sharding

You can define the size of the cache object's storage sharding set as needed. The default is 1024. When the amount of data is small, define a small sharding set size, you can get memory improvement. When the data volume is large, you can define a large sharding set size to further improve performance.

cache.NewMemCache(cache.WithShards(8))
ExpiredCallback

You can define a callback function func(k string, v interface{}) error that will be executed when a key-value expires (only expiration triggers, delete or override does not trigger).

import (
	"fmt"
	"github.com/fanjindong/go-cache"
)

func main() {
    f := func(k string, v interface{}) error{
        fmt.Println("ExpiredCallback", k, v)
        return nil
    }
    c := cache.NewMemCache(cache.WithExpiredCallback(f))
    c.Set("k", 1)
    c.Set("kWithEx", 1, cache.WithEx(1*time.Second))
    time.sleep(1 * time.Second)
    c.Get("k")       // 1, true
    c.Get("kWithEx") // nil, false
    // output: ExpiredCallback kWithEx, 1
}
ClearInterval

go-cache clears expired cache objects periodically. The default interval is 1 second. Depending on your business scenario, choosing an appropriate cleanup interval can further improve performance.

import "github.com/fanjindong/go-cache"

func main() {
    c := cache.NewMemCache(cache.WithClearInterval(1*time.Minute))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config added in v0.0.4

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

func NewConfig added in v0.0.4

func NewConfig() *Config

type ExpiredCallback added in v0.0.4

type ExpiredCallback func(k string, v interface{}) error

ExpiredCallback Callback the function when the key-value pair expires Note that it is executed after expiration

type ICache

type ICache interface {
	//Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type.
	//Any previous time to live associated with the key is discarded on successful SET operation.
	//Example:
	//c.Set("demo", 1)
	//c.Set("demo", 1, WithEx(10*time.Second))
	//c.Set("demo", 1, WithEx(10*time.Second), WithNx())
	Set(k string, v interface{}, opts ...SetIOption) bool
	//Get the value of key.
	//If the key does not exist the special value nil,false is returned.
	//Example:
	//c.Get("demo") //nil, false
	//c.Set("demo", "value")
	//c.Get("demo") //"value", true
	Get(k string) (interface{}, bool)
	//GetSet Atomically sets key to value and returns the old value stored at key.
	//Returns nil,false when key not exists.
	//Example:
	//c.GetSet("demo", 1) //nil,false
	//c.GetSet("demo", 2) //1,true
	GetSet(k string, v interface{}, opts ...SetIOption) (interface{}, bool)
	//GetDel Get the value of key and delete the key.
	//This command is similar to GET, except for the fact that it also deletes the key on success.
	//Example:
	//c.Set("demo", "value")
	//c.GetDel("demo") //"value", true
	//c.GetDel("demo") //nil, false
	GetDel(k string) (interface{}, bool)
	//Del Removes the specified keys. A key is ignored if it does not exist.
	//Return the number of keys that were removed.
	//Example:
	//c.Set("demo1", "1")
	//c.Set("demo2", "1")
	//c.Del("demo1", "demo2", "demo3") //2
	Del(keys ...string) int
	//DelExpired Only delete when key expires
	//Example:
	//c.Set("demo1", "1")
	//c.Set("demo2", "1", WithEx(1*time.Second))
	//time.Sleep(1*time.Second)
	//c.DelExpired("demo1", "demo2") //true
	DelExpired(k string) bool
	//Exists Returns if key exists.
	//Return the number of exists keys.
	//Example:
	//c.Set("demo1", "1")
	//c.Set("demo2", "1")
	//c.Exists("demo1", "demo2", "demo3") //2
	Exists(keys ...string) bool
	//Expire Set a timeout on key.
	//After the timeout has expired, the key will automatically be deleted.
	//Return false if the key not exist.
	//Example:
	//c.Expire("demo", 1*time.Second) // false
	//c.Set("demo", "1")
	//c.Expire("demo", 1*time.Second) // true
	Expire(k string, d time.Duration) bool
	//ExpireAt has the same effect and semantic as Expire, but instead of specifying the number of seconds representing the TTL (time to live),
	//it takes an absolute Unix Time (seconds since January 1, 1970). A Time in the past will delete the key immediately.
	//Return false if the key not exist.
	//Example:
	//c.ExpireAt("demo", time.Now().Add(10*time.Second)) // false
	//c.Set("demo", "1")
	//c.ExpireAt("demo", time.Now().Add(10*time.Second)) // true
	ExpireAt(k string, t time.Time) bool
	//Persist Remove the existing timeout on key.
	//Return false if the key not exist.
	//Example:
	//c.Persist("demo") // false
	//c.Set("demo", "1")
	//c.Persist("demo") // true
	Persist(k string) bool
	//Ttl Returns the remaining time to live of a key that has a timeout.
	//Returns 0,false if the key does not exist or if the key exist but has no associated expire.
	//Example:
	//c.Set("demo", "1")
	//c.Ttl("demo") // 0,false
	//c.Set("demo", "1", WithEx(10*time.Second))
	//c.Ttl("demo") // 10*time.Second,true
	Ttl(k string) (time.Duration, bool)
	// ToMap converts the current cache into a map with string keys and interface{} values.
	// Where the keys are the field names (as strings) and the values are the corresponding data.
	// Returns:
	//   A map[string]interface{} where each entry corresponds to a field of the object and its value.
	// Example:
	// c.Set("a", 1)
	// c.Set("b", "uu")
	// c.ToMap() return {"a":1,"b":"uu"}
	// c.Expire("a", 1*time.Second)
	// when sleep(1*time.Second)
	// c.ToMap() return {"b":"uu"}
	ToMap() map[string]interface{}
}

func NewMemCache

func NewMemCache(opts ...ICacheOption) ICache

type ICacheOption

type ICacheOption func(conf *Config)

ICacheOption The option used to create the cache object

func WithClearInterval added in v0.0.4

func WithClearInterval(d time.Duration) ICacheOption

WithClearInterval set custom clear interval. Interval for clearing expired key-value pairs. The default value is 1 second If the d is 0, the periodic clearing function is disabled

func WithExpiredCallback added in v0.0.4

func WithExpiredCallback(ec ExpiredCallback) ICacheOption

WithExpiredCallback set custom expired callback function This callback function is called when the key-value pair expires

func WithHash added in v0.0.4

func WithHash(hash IHash) ICacheOption

WithHash set custom hash key function

func WithShards added in v0.0.4

func WithShards(shards int) ICacheOption

WithShards set custom size of sharding. Default is 1024 The larger the size, the smaller the lock force, the higher the concurrency performance, and the higher the memory footprint, so try to choose a size that fits your business scenario

type IHash added in v0.0.4

type IHash interface {
	Sum64(string) uint64
}

IHash is responsible for generating unsigned, 64-bit hash of provided string. IHash should minimize collisions (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. you can use FarmHash family).

type IItem added in v0.0.2

type IItem interface {
	Expired() bool
	CanExpire() bool
	SetExpireAt(t time.Time)
}

type Item

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

func (*Item) CanExpire added in v0.0.2

func (i *Item) CanExpire() bool

func (*Item) Expired

func (i *Item) Expired() bool

func (*Item) SetExpireAt added in v0.0.2

func (i *Item) SetExpireAt(t time.Time)

type MemCache

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

func (MemCache) Del

func (c MemCache) Del(ks ...string) int

func (MemCache) DelExpired

func (c MemCache) DelExpired(k string) bool

DelExpired Only delete when key expires

func (MemCache) Exists

func (c MemCache) Exists(ks ...string) bool

func (MemCache) Expire

func (c MemCache) Expire(k string, d time.Duration) bool

func (MemCache) ExpireAt

func (c MemCache) ExpireAt(k string, t time.Time) bool

func (MemCache) Get

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

func (MemCache) GetDel

func (c MemCache) GetDel(k string) (interface{}, bool)

func (MemCache) GetSet

func (c MemCache) GetSet(k string, v interface{}, opts ...SetIOption) (interface{}, bool)

func (MemCache) Persist

func (c MemCache) Persist(k string) bool

func (MemCache) Set

func (c MemCache) Set(k string, v interface{}, opts ...SetIOption) bool

func (MemCache) ToMap added in v0.0.6

func (c MemCache) ToMap() map[string]interface{}

func (MemCache) Ttl

func (c MemCache) Ttl(k string) (time.Duration, bool)

type SetIOption

type SetIOption func(ICache, string, IItem) bool

SetIOption The option used to cache set

func WithEx

func WithEx(d time.Duration) SetIOption

WithEx Set the specified expire time, in time.Duration.

func WithExAt

func WithExAt(t time.Time) SetIOption

WithExAt Set the specified expire deadline, in time.Time.

Jump to

Keyboard shortcuts

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