cacheit

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2023 License: MIT Imports: 10 Imported by: 0

README

cacheit

GitHub go.mod Go version Go Report Card Unit-Tests Coverage Status Go Reference

GO 缓存库,支持 go-redis 和 go-cache 作为缓存驱动。它提供了一个简单的接口,允许您轻松地在您的项目中实现缓存。

安装

使用以下命令将 cacheit 添加到您的 Go 项目中:

go get github.com/feymanlee/cacheit

接口定义

type Driver[V any] interface {
    // Add Store an item in the cache if the key doesn't exist.
    Add(key string, value V, t time.Duration) error
    // Set Store an item in the cache for a given number of seconds.
    Set(key string, value V, t time.Duration) error
    // SetMany Store multiple items in the cache for a given number of seconds.
    SetMany(many []Many[V]) error
    // Forever Store an item in the cache indefinitely.
    Forever(key string, value V) error
    // Forget Remove an item from the cache.
    Forget(key string) error
    // Flush Remove all items from the cache.
    Flush() error
    // Get Retrieve an item from the cache by key.
    Get(key string) (V, error)
    // Has Determined if an item exists in the cache.
    Has(key string) (bool, error)
    // Many Retrieve multiple items from the cache by key.
    // Items not found in the cache will have a nil value.
    Many(keys []string) (map[string]V, error)
    // SetNumber set the int64 value of an item in the cache.
    SetNumber(key string, value V, t time.Duration) error
    // Increment the value of an item in the cache.
    Increment(key string, n V) (V, error)
    // Decrement the value of an item in the cache.
    Decrement(key string, n V) (V, error)
    // Remember Get an item from the cache, or execute the given Closure and store the result.
    Remember(key string, ttl time.Duration, callback func() (V, error)) (V, error)
    // RememberForever Get an item from the cache, or execute the given Closure and store the result forever.
    RememberForever(key string, callback func() (V, error)) (V, error)
    // TTL Get cache ttl
    TTL(key string) (time.Duration, error)
    // WithCtx with context
    WithCtx(ctx context.Context) Driver[V]
}

Usage

Redis Driver
// 初始化 Redis 客户端
redisClient := redis.NewClient(&redis.Options{
    Addr:     "localhost:6379",
    Password: "",
    DB:       0,
})

// 创建缓存驱动实例
driver, err := cacheit.New[string](cacheit.DriverRedis, 
	cacheit.WithRedisClient(redisClient), 
	cacheit.WithPrefix("myapp"),
	cacheit.WithSerializer(cacheit.JsonSerializer)
)
if err != nil {
    log.Fatal(err)
}
Go-cache Driver
// go-cache 客户端
memCache := gocache.New(5*time.Minute, 10*time.Minute)
// 初始化 GoCacheDriver
driver, _ := New[string](DriverMemory, 
	WithMemCache(memCache),
    cacheit.WithPrefix("myapp")
)

Add Cache
err = driver.Add("key", "value", time.Minute*10)
if err != nil {
    log.Println("Error adding cache:", err)
}
Set Cache
err = driver.Set("key2", "value2", time.Minute*5)
if err != nil {
    log.Println("Error setting cache:", err)
}
Get Cache
value, err := driver.Get("key2")
if err != nil {
    log.Println("Error getting cache:", err)
} else {
    log.Println("Cache value:", value)
}
Batch Set Cache
err = driver.SetMany([]cacheit.Many[string]{
    {Key: "key3", Value: "value3", TTL: time.Minute * 10},
    {Key: "key4", Value: "value4", TTL: time.Minute * 15},
})
if err != nil {
    log.Println("Error setting many caches:", err)
}
Batch Get Cache
values, err := driver.Many([]string{"key2", "key3", "key4"})
if err != nil {
    log.Println("Error getting many caches:", err)
} else {
    log.Println("Cache values:", values)
}
Set Cache Not Expired
err = driver.Forever("key5", "value5")
if err != nil {
    log.Println("Error storing cache forever:", err)
}
Remove Cache
err = driver.Forget("key")
if err != nil {
    log.Println("Error removing cache:", err)
}
Remove All Cache
err = driver.Flush()
if err != nil {
    log.Println("Error flushing cache:", err)
}
Determined Cache Has Existed
has, err := driver.Has("key2")
if err != nil {
    log.Println("Error checking if cache exists:", err)
} else if has {
    log.Println("Cache key2 exists")
} else {
    log.Println("Cache key2 does not exist")
}
Set Numeric Cache
err = driver.SetNumber("number_key", 1, time.Minute*10)
if err != nil {
    log.Println("Error setting number cache:", err)
}
Increment Numeric Cache
newValue, err := driver.Increment("number_key", 1)
if err != nil {
    log.Println("Error incrementing cache value:", err)
} else {
    log.Println("Incremented cache value:", newValue)
}
Decrement Numeric Cache
newValue, err := driver.Increment("number_key", 1)
if err != nil {
    log.Println("Error incrementing cache value:", err)
} else {
    log.Println("Incremented cache value:", newValue)
}
Get Cache Or Set It If Cache Not Exist
rememberValue, err := driver.Remember("remember_key", time.Minute*10, func() (string, error) {
    time.Sleep(time.Millisecond * 50)
    return "remember_value", nil
})
if err != nil {
    log.Println("Error remembering cache:", err)
} else {
    log.Println("Remember cache value:", rememberValue)
}
Retrieve The Cache Or Set It To Never Expire If The Cache Does Not Exist
rememberForeverValue, err := driver.RememberForever("remember_forever_key", func() (string, error) {
		// 模拟数据获取
		time.Sleep(time.Millisecond * 50)
		return "remember_forever_value", nil
	})
	if err != nil {
		log.Println("Error remembering cache forever:", err)
	} else {
		log.Println("Remember cache value forever:", rememberForeverValue)
	}
Get Cache TTL
ttl, err := driver.TTL("key2")
if err != nil {
    log.Println("Error getting cache TTL:", err)
} else {
    log.Println("Cache TTL:", ttl)
}
With Context
err = driver.WithCtx(context.TODO()).Set("key2", "value2", time.Minute*5)
if err != nil {
    log.Println("Error setting cache:", err)
}

更多功能

请查阅源代码以了解更多功能和用法。

贡献

欢迎向项目贡献代码、提交 bug 报告或提出新功能建议。请务必遵循贡献指南。

许可证

本项目基于 MIT 许可证 发布。

Documentation

Index

Constants

View Source
const (
	// NoExpirationTTL no expiration ttl
	NoExpirationTTL = time.Duration(-1)
	// ItemNotExistedTTL item not existed ttl
	ItemNotExistedTTL = time.Duration(-2)
)

Variables

View Source
var (
	ErrCacheMiss    = errors.New("cache not exists")
	ErrCacheExisted = errors.New("cache already existed")
)

Functions

This section is empty.

Types

type Driver

type Driver[V any] interface {
	// Add Store an item in the cache if the key doesn't exist.
	Add(key string, value V, t time.Duration) error
	// Set Store an item in the cache for a given number of seconds.
	Set(key string, value V, t time.Duration) error
	// SetMany Store multiple items in the cache for a given number of seconds.
	SetMany(many []Many[V]) error
	// Forever Store an item in the cache indefinitely.
	Forever(key string, value V) error
	// Forget Remove an item from the cache.
	Forget(key string) error
	// Flush Remove all items from the cache.
	Flush() error
	// Get Retrieve an item from the cache by key.
	Get(key string) (V, error)
	// Has Determined if an item exists in the cache.
	Has(key string) (bool, error)
	// Many Retrieve multiple items from the cache by key.
	// Items not found in the cache will have a nil value.
	Many(keys []string) (map[string]V, error)
	// SetNumber set the int64 value of an item in the cache.
	SetNumber(key string, value V, t time.Duration) error
	// Increment the value of an item in the cache.
	Increment(key string, n V) (V, error)
	// Decrement the value of an item in the cache.
	Decrement(key string, n V) (V, error)
	// Remember Get an item from the cache, or execute the given Closure and store the result.
	Remember(key string, ttl time.Duration, callback func() (V, error)) (V, error)
	// RememberForever Get an item from the cache, or execute the given Closure and store the result forever.
	RememberForever(key string, callback func() (V, error)) (V, error)
	// TTL Get cache ttl
	TTL(key string) (time.Duration, error)
	// WithCtx with context
	WithCtx(ctx context.Context) Driver[V]
}

Driver cache driver interface

func New

func New[V any](driver DriverType, optionFns ...OptionFunc) (Driver[V], error)

type DriverType

type DriverType string

DriverType DriverType

const (
	// DriverRedis type redis
	DriverRedis DriverType = "redis"
	// DriverMemory type memory
	DriverMemory DriverType = "memory"
)

type GoCacheDriver

type GoCacheDriver[V any] struct {
	// contains filtered or unexported fields
}

GoCacheDriver go-cache driver implemented

func (*GoCacheDriver[V]) Add

func (d *GoCacheDriver[V]) Add(key string, value V, t time.Duration) error

func (*GoCacheDriver[V]) Decrement added in v0.1.0

func (d *GoCacheDriver[V]) Decrement(key string, n V) (ret V, err error)

func (*GoCacheDriver[V]) Flush

func (d *GoCacheDriver[V]) Flush() error

func (*GoCacheDriver[V]) Forever

func (d *GoCacheDriver[V]) Forever(key string, value V) error

func (*GoCacheDriver[V]) Forget

func (d *GoCacheDriver[V]) Forget(key string) error

func (*GoCacheDriver[V]) Get

func (d *GoCacheDriver[V]) Get(key string) (result V, err error)

func (*GoCacheDriver[V]) Has

func (d *GoCacheDriver[V]) Has(key string) (bool, error)

func (*GoCacheDriver[V]) Increment added in v0.1.0

func (d *GoCacheDriver[V]) Increment(key string, n V) (ret V, err error)

func (*GoCacheDriver[V]) Many

func (d *GoCacheDriver[V]) Many(keys []string) (map[string]V, error)

func (*GoCacheDriver[V]) Remember

func (d *GoCacheDriver[V]) Remember(key string, ttl time.Duration, callback func() (V, error)) (result V, err error)

func (*GoCacheDriver[V]) RememberForever

func (d *GoCacheDriver[V]) RememberForever(key string, callback func() (V, error)) (V, error)

func (*GoCacheDriver[V]) Set added in v0.1.0

func (d *GoCacheDriver[V]) Set(key string, value V, t time.Duration) error

func (*GoCacheDriver[V]) SetMany added in v0.1.0

func (d *GoCacheDriver[V]) SetMany(many []Many[V]) error

func (*GoCacheDriver[V]) SetNumber added in v0.1.0

func (d *GoCacheDriver[V]) SetNumber(key string, value V, t time.Duration) error

func (*GoCacheDriver[V]) TTL added in v0.1.0

func (d *GoCacheDriver[V]) TTL(key string) (ttl time.Duration, err error)

func (*GoCacheDriver[V]) WithCtx added in v0.1.0

func (d *GoCacheDriver[V]) WithCtx(ctx context.Context) Driver[V]

type JSONSerializer

type JSONSerializer struct{}

JSONSerializer json serializer

func (*JSONSerializer) Serialize

func (d *JSONSerializer) Serialize(v any) ([]byte, error)

Serialize Serialize data

func (*JSONSerializer) UnSerialize

func (d *JSONSerializer) UnSerialize(data []byte, v any) error

UnSerialize UnSerialize data

type Many

type Many[V any] struct {
	Key   string
	Value V
	TTL   time.Duration
}

Many type many

type OptionFunc

type OptionFunc func(driver *baseDriver) error

func WithMemCache

func WithMemCache(memCache *gocache.Cache) OptionFunc

WithMemCache with a go-cache client

func WithPrefix

func WithPrefix(prefix string) OptionFunc

WithPrefix set a cache prefix

func WithRedisClient

func WithRedisClient(redis *redis.Client) OptionFunc

WithRedisClient set a redis client

func WithSerializer

func WithSerializer(serializer Serializer) OptionFunc

WithSerializer set a cache serializer

type RedisDriver

type RedisDriver[V any] struct {
	// contains filtered or unexported fields
}

RedisDriver go-redis driver implemented

func (*RedisDriver[V]) Add

func (d *RedisDriver[V]) Add(key string, value V, t time.Duration) error

func (*RedisDriver[V]) Decrement added in v0.1.0

func (d *RedisDriver[V]) Decrement(key string, n V) (ret V, err error)

func (*RedisDriver[V]) Flush

func (d *RedisDriver[V]) Flush() error

func (*RedisDriver[V]) Forever

func (d *RedisDriver[V]) Forever(key string, value V) error

func (*RedisDriver[V]) Forget

func (d *RedisDriver[V]) Forget(key string) error

func (*RedisDriver[V]) Get

func (d *RedisDriver[V]) Get(key string) (V, error)

func (*RedisDriver[V]) Has

func (d *RedisDriver[V]) Has(key string) (bool, error)

func (*RedisDriver[V]) Increment added in v0.1.0

func (d *RedisDriver[V]) Increment(key string, n V) (ret V, err error)

func (*RedisDriver[V]) Many

func (d *RedisDriver[V]) Many(keys []string) (map[string]V, error)

func (*RedisDriver[V]) Remember

func (d *RedisDriver[V]) Remember(key string, ttl time.Duration, callback func() (V, error)) (result V, err error)

func (*RedisDriver[V]) RememberForever

func (d *RedisDriver[V]) RememberForever(key string, callback func() (V, error)) (V, error)

func (*RedisDriver[V]) Set added in v0.1.0

func (d *RedisDriver[V]) Set(key string, value V, t time.Duration) error

func (*RedisDriver[V]) SetMany added in v0.1.0

func (d *RedisDriver[V]) SetMany(many []Many[V]) error

func (*RedisDriver[V]) SetNumber added in v0.1.0

func (d *RedisDriver[V]) SetNumber(key string, value V, t time.Duration) error

func (*RedisDriver[V]) TTL added in v0.1.0

func (d *RedisDriver[V]) TTL(key string) (ttl time.Duration, err error)

func (*RedisDriver[V]) WithCtx added in v0.1.0

func (d *RedisDriver[V]) WithCtx(ctx context.Context) Driver[V]

type Serializer

type Serializer interface {
	Serialize(v any) ([]byte, error)
	UnSerialize(data []byte, v any) error
}

Serializer serializer interface

Jump to

Keyboard shortcuts

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