cacheit

package module
v0.5.2 Latest Latest
Warning

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

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

README

cacheit

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

GO 缓存库,支持 go-redisgo-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 zero value.
    Many(keys []string) (map[string]V, error)
    // SetNumber set the number 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]
    // WithWithSerializer with cache serializer
    WithSerializer(serializer Serializer) Driver[V]
}

Usage

Base Usage
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/feymanlee/cacheit"
	"github.com/go-redis/redis/v8"
	gocache "github.com/patrickmn/go-cache"
)

func main() {
	redisClient := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	err := cacheit.RegisterRedisDriver("redis_test", redisClient, "cache_prefix")
	if err != nil {
		log.Fatal(err)
	}
	// go-cache 客户端
	memCache := gocache.New(5*time.Minute, 10*time.Minute)
	err = cacheit.RegisterGoCacheDriver("memory_test", memCache, "cache_prefix")
	if err != nil {
		log.Fatal(err)
	}
	// set default cache
	cacheit.SetDefault("redis_test")

	driver, err := cacheit.Use[string]("memory_test")
	if err != nil {
		log.Fatal(err)
	}
	
	err = driver.Set("cache_key", "cache_value", time.Minute)
	if err != nil {
		log.Fatal(err)
	}
	
	get, err := cacheit.UseDefault[string]().Get("cache_key")
	if err != nil {
		return
	}
	fmt.Println(get)
}
Add

Store an item in the cache if the key doesn't exist.

err = driver.Add("key", "value", time.Minute*10)
if err != nil {
log.Println("Error adding cache:", err)
}
Set

Store an item in the cache for a given number of seconds.

err = driver.Set("key2", "value2", time.Minute*5)
if err != nil {
log.Println("Error setting cache:", err)
}
Get

Retrieve an item from the cache by key.

value, err := driver.Get("key2")
if err != nil {
log.Println("Error getting cache:", err)
} else {
log.Println("Cache value:", value)
}
SetMany

Store multiple items in the cache for a given number of seconds.

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)
}
Many

Retrieve multiple items from the cache by key. Items not found in the cache will have a zero value.

values, err := driver.Many([]string{"key2", "key3", "key4"})
if err != nil {
log.Println("Error getting many caches:", err)
} else {
log.Println("Cache values:", values)
}
Forever

Store an item in the cache indefinitely.

err = driver.Forever("key5", "value5")
if err != nil {
log.Println("Error storing cache forever:", err)
}
Forget

Remove an item from the cache.

err = driver.Forget("key")
if err != nil {
log.Println("Error removing cache:", err)
}
Flush

Remove all items from the cache.

err = driver.Flush()
if err != nil {
log.Println("Error flushing cache:", err)
}
Has

Determined if an item exists in the cache.

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")
}
SetNumber

Set the number value of an item in the cache.

err = driver.SetNumber("number_key", 1, time.Minute*10)
if err != nil {
log.Println("Error setting number cache:", err)
}
Increment

Increment the value of an item in the 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)
}
Increment
newValue, err := driver.Increment("number_key", 1)
if err != nil {
log.Println("Error incrementing cache value:", err)
} else {
log.Println("Incremented cache value:", newValue)
}
Remember
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)
}
RememberForever
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)
}
TTL
ttl, err := driver.TTL("key2")
if err != nil {
log.Println("Error getting cache TTL:", err)
} else {
log.Println("Cache TTL:", ttl)
}
WithCtx
err = driver.WithCtx(context.TODO()).Set("key2", "value2", time.Minute*5)
if err != nil {
log.Println("Error setting cache:", err)
}

更多功能

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

贡献

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

鸣谢

GoLand A Go IDE with extended support for JavaScript, TypeScript, and databases。

特别感谢 JetBrains 为开源项目提供免费的 GoLand 等 IDE 的授权

许可证

本项目基于 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

func RegisterGoCacheDriver added in v0.3.0

func RegisterGoCacheDriver(driverName string, memCache *gocache.Cache, cacheKeyPrefix string) error

RegisterGoCacheDriver registers a GoCache driver with the given driverName. This function creates a new driver based on the provided go-cache client and registers it in registerDrivers.

func RegisterRedisDriver added in v0.3.0

func RegisterRedisDriver(driverName string, redis *redis.Client, cacheKeyPrefix string) error

RegisterRedisDriver registers a Redis driver with the given driverName. This function creates a new driver based on the provided redis client and registers it in registerDrivers.

func SetDefault added in v0.3.0

func SetDefault(driverName string)

SetDefault set default driver

func UnSetDefault added in v0.3.0

func UnSetDefault()

UnSetDefault cancel set default driver

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
	// Del Remove an item from the cache alia Forget.
	Del(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), force bool) (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), force bool) (V, error)
	// RememberMany Get many item from the cache, or execute the given Closure and store the result.
	RememberMany(keys []string, ttl time.Duration, callback func(notHitKeys []string) (map[string]V, error), force bool) (map[string]V, error)
	// TTL Get cache ttl
	TTL(key string) (time.Duration, error)
	// WithCtx with context
	WithCtx(ctx context.Context) Driver[V]
	// WithSerializer with cache serializer
	WithSerializer(serializer Serializer) Driver[V]
}

Driver cache driver interface

func Use added in v0.3.0

func Use[V any](driverName string) (Driver[V], error)

Use select a driver

func UseDefault added in v0.3.0

func UseDefault[V any]() Driver[V]

UseDefault user default driver

type DriverType

type DriverType string

DriverType DriverType

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]) Del added in v0.5.1

func (d *GoCacheDriver[V]) Del(key string) 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), force bool) (result V, err error)

func (*GoCacheDriver[V]) RememberForever

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

func (*GoCacheDriver[V]) RememberMany added in v0.4.0

func (d *GoCacheDriver[V]) RememberMany(keys []string, ttl time.Duration, callback func(notHitKeys []string) (map[string]V, error), force bool) (map[string]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]

func (*GoCacheDriver[V]) WithSerializer added in v0.3.0

func (d *GoCacheDriver[V]) WithSerializer(serializer Serializer) 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

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]) Del added in v0.5.1

func (d *RedisDriver[V]) Del(key string) 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), force bool) (result V, err error)

func (*RedisDriver[V]) RememberForever

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

func (*RedisDriver[V]) RememberMany added in v0.4.0

func (d *RedisDriver[V]) RememberMany(keys []string, ttl time.Duration, callback func(notHitKeys []string) (map[string]V, error), force bool) (map[string]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]

func (*RedisDriver[V]) WithSerializer added in v0.3.0

func (d *RedisDriver[V]) WithSerializer(serializer Serializer) 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