cacheya

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2024 License: MIT Imports: 8 Imported by: 0

README

cacheya

介绍

Golang 缓存封装,支持Context、内存、Redis多种缓存适配,实现便捷的 Cache-Aside 操作

基本使用


type TestObject struct {
    Id   string
    A    float32
    B    uint32
}


ctx := context.Background()

// 初始化:Redis缓存
opt := &redis.Options{
    Addr:     "127.0.0.1:6379",
}
client := redis.NewClient(opt)

adapter := goredis.NewRedisCache(client)
manager := NewCacheManager[string, *TestObject]("TEST_OBJECT", adapter)   // 范型中第一个指定id的类型,第二个指定缓存的对象

// 初始化:内存缓存
client, _ := ristretto.NewCache(
    &ristretto.Config{
        NumCounters: 1e7,  // number of keys to track frequency of (10M).
        MaxCost:     10e7, // maximum cost of cache (100M).
        BufferItems: 64,   // number of keys per Get buf
    },
)
adapter := memory.NewRistrettoCache(client)
manager := NewCacheManager[string, *TestObject]("TEST_OBJECT", adapter)

// 初始化:Context缓存
// 注意,使用时需要在服务内ctx生命周期开始时(比如grpc的中间件中),使用WithCtxCache对ctx开启缓存,否则无效
adapter := ctxcache.NewContextCache()
manager := NewCacheManager[string, *TestObject]("TEST_OBJECT", adapter)

// 单数据操作
r, c, err := manager.Get(ctx, "1")                 // Get
err = manager.Set(ctx, "2", &TestObject{Id: "2"})  // Set
err = manager.Del(ctx, "1")                        // Del
r, err = manager.Load(                             // Cache-Aside
    ctx, "1", func(k string) (*TestObject, error) {
        // 这里实现回源的代码
    },
)

// 批量操作
r, err := manager.MGet(ctx, []string{"1", "2"})    // MGet
err = manager.MSet(ctx, kv)                        // MSet
err = manager.MDel(ctx, []string{"1", "2"})        // MDel
r, err = manager.MLoad(                            // Multi Cache-Aside
    ctx, []string{"1", "2"}, func(ks []string) (map[string]*TestObject, error) {
        // 这里实现回源的代码
    },
)

缓存基本类型

type TestStringValue string
manager := NewCacheManager[string, TestStringValue]("TEST_STRING", adapter)

r, err = manager.Load(                             // Cache-Aside
    ctx, "1", func(k string) (TestStringValue, error) {
        // 这里实现回源的代码
    },
)
r, err = manager.MLoad(                            // Multi Cache-Aside
    ctx, []string{"1", "2"}, func(ks []string) (map[string]TestStringValue, error) {
        // 这里实现回源的代码
    },
)

支持的参数

type Config struct {
    version    string        // 缓存版本,调整缓存内容时需要升级版本,避免存量缓存的影响,默认:1
    ttl        time.Duration // 缓存超时时间,默认:1h
    ttlJitter  time.Duration // 缓存超时时间随机间隔上限,默认:10s
    cacheNil   bool          // 是否缓存nil,默认:true
    keyBuilder Builder       // 缓存key生成函数,默认:{prefix}:{key}
    marshaller Marshaller    // 序列化实现,默认:JSON
    compressor Compressor    // 压缩实现,默认:Noop
    metrics    Metrics       // 监控埋点,默认:Noop
    logger     Logger        // 日志,默认:Noop
}

manager := NewCacheManager[string, *TestObject]("TEST_OBJECT_PTR", adapter, TTL(CacheTTL, CacheJitter))

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultKeyBuilder

func DefaultKeyBuilder(ctx context.Context, name string, key any) string

Types

type Builder

type Builder func(ctx context.Context, prefix string, k any) string

type CacheAdaptor

type CacheAdaptor interface {
	Name() string

	MGet(ctx context.Context, keys []string) (map[string][]byte, error)
	MSet(ctx context.Context, kvMap map[string][]byte, ttl time.Duration) error
	MDel(ctx context.Context, keys []string) error
}

type CacheManager

type CacheManager[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func NewCacheManager

func NewCacheManager[K comparable, V any](name string, adaptor CacheAdaptor, opts ...Option) *CacheManager[K, V]

func (*CacheManager[K, V]) Del

func (l *CacheManager[K, V]) Del(ctx context.Context, key K) error

func (*CacheManager[K, V]) Get

func (l *CacheManager[K, V]) Get(ctx context.Context, key K) (result V, isCached bool, err error)

func (*CacheManager[K, V]) Load

func (l *CacheManager[K, V]) Load(ctx context.Context, key K, loader SingleDataLoader[K, V]) (r V, e error)

Load Cache-Aside 实现,单个查询

func (*CacheManager[K, V]) MDel

func (l *CacheManager[K, V]) MDel(ctx context.Context, keys []K) (err error)

func (*CacheManager[K, V]) MGet

func (l *CacheManager[K, V]) MGet(ctx context.Context, keys []K) (result map[K]V, err error)

func (*CacheManager[K, V]) MLoad

func (l *CacheManager[K, V]) MLoad(ctx context.Context, keys []K, loader MultiDataLoader[K, V]) (map[K]V, error)

MLoad Cache-Aside 实现,批量查询,返回引用(返回的map中不会有为nil的value)

func (*CacheManager[K, V]) MSet

func (l *CacheManager[K, V]) MSet(ctx context.Context, kv map[K]V) (err error)

func (*CacheManager[K, V]) Set

func (l *CacheManager[K, V]) Set(ctx context.Context, k K, v V) error

type CacheValue

type CacheValue[V any] struct {
	Object  V      `json:"o"`
	Version string `json:"v"`
}

type Compressor

type Compressor interface {
	Encode([]byte) ([]byte, error)
	Decode([]byte) ([]byte, error)
}

type Config

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

type Logger

type Logger interface {
	Debug(ctx context.Context, message string, fields map[string]any)
	Info(ctx context.Context, message string, fields map[string]any)
	Warn(ctx context.Context, message string, fields map[string]any)
	Error(ctx context.Context, message string, fields map[string]any)
}

Logger 日志接口

func NewNoopLogger

func NewNoopLogger() Logger

type Marshaller

type Marshaller interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
}

type Metrics

type Metrics interface {
	Counter(ctx context.Context, name string, inc float64, labels map[string]string)
	Timer(ctx context.Context, name string, seconds float64, labels map[string]string)
	Value(ctx context.Context, name string, value float64, labels map[string]string)
}

Metrics 监控埋点接口

func NewNoopMetrics

func NewNoopMetrics() Metrics

type MultiDataLoader

type MultiDataLoader[K comparable, V any] func(keys []K) (map[K]V, error)

type Option

type Option func(*Config)

func CacheNil

func CacheNil(cacheNil bool) Option

func KeyBuilder

func KeyBuilder(f Builder) Option

func SetCompressor

func SetCompressor(compressor Compressor) Option

func SetLogger

func SetLogger(logger Logger) Option

func SetMarshaller

func SetMarshaller(marshaller Marshaller) Option

func SetMetrics

func SetMetrics(metrics Metrics) Option

func TTL

func TTL(ttl time.Duration, jitter time.Duration) Option

func Version

func Version(version string) Option

type SingleDataLoader

type SingleDataLoader[K comparable, V any] func(k K) (V, error)

Directories

Path Synopsis
adaptor

Jump to

Keyboard shortcuts

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