cache

package module
v2.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2024 License: MIT Imports: 10 Imported by: 2

README

go-cache

Build Status

常用的缓存库,提供各类常用的缓存函数,通过简单的组合则可实现支持TTL、数据压缩的多级缓存

Store

默认提供了两种常用的支持ttl的store:

  • bigcache: 基于bigcache的内存store,但仅支持实例初始化时指定ttl,不可每个key设置不同的ttl
  • redis: 基于redis的store,支持实例化时指定默认的ttl,并可针对不同的key设置不同的ttl

示例

c, err := cache.New(
    10*time.Minute,
    // 数据清除时间窗口(仅用于bigcache),默认为1秒
    cache.CacheCleanWindowOption(5*time.Second),
    // 最大的entry大小,用于缓存的初始大小,默认为500(仅用于bigcache)
    cache.CacheMaxEntrySizeOption(1024),
    // 最大使用的内存大小(MB),默认为0不限制(仅用于bigcache)
    cache.CacheHardMaxCacheSizeOption(10),
    // 指定key的前缀
    cache.CacheKeyPrefixOption("prefix:"),
    // 指定二级缓存
    cache.CacheSecondaryStoreOption(cache.NewRedisStore(redisClient)),
    // 指定不同的缓存使用不同的ttl
    cache.CacheMultiTTLOption([]time.Duration{
        // 一级缓存有效期
        time.Minute,
        // 二级缓存有效期
        10 * time.Minute,
    }),
)

RedisCache

封装了一些常用的redis函数,保证所有缓存均需要指定ttl,并支持指定前缀。

指定缓存Key的前缀
// 创建一个redis的client
client := newRedisClient()
opts := []goCache.RedisCacheOption{
    goCache.RedisCachePrefixOption("prefix:"),
}
c := goCache.NewRedisCache(client, opts...)
Redis Session

用于elton中session的redis缓存。

// 创建一个redis的client
client := newRedisClient()
ss := goCache.NewRedisSession(client)
// 设置前缀
ss.SetPrefix(redisConfig.Prefix + "ss:")

Documentation

Overview

Copyright 2022 tree xie

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (
	// CompressNone compress none
	CompressNone byte = iota
	// Compressed compress
	Compressed
)

Variables

View Source
var ErrIsNil = errors.New("Data is nil")
View Source
var ErrKeyIsNil = errors.New("Key is nil")

Functions

func Get

func Get[T any](ctx context.Context, c *Cache, key string) (*T, error)

Types

type Cache

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

func New

func New(ttl time.Duration, opts ...CacheOption) (*Cache, error)

New creates a new cache with default ttl

func (*Cache) Close

func (c *Cache) Close(ctx context.Context) error

Close closes all stores of cache

func (*Cache) Delete

func (c *Cache) Delete(ctx context.Context, key string) error

Delete deletes all the data from all stores

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, key string, value any) error

Get gets the value from cache and unmarshals it

func (*Cache) GetAndTTL

func (c *Cache) GetAndTTL(ctx context.Context, key string, value any) (time.Duration, error)

GetAndTTL gets the value from cache and unmarshals it, and returns the ttl of value

func (*Cache) GetBytes

func (c *Cache) GetBytes(ctx context.Context, key string) ([]byte, error)

GetBytes gets the data from cache

func (*Cache) GetBytesAndTTL

func (c *Cache) GetBytesAndTTL(ctx context.Context, key string) ([]byte, time.Duration, error)

GetBytesAndTTL gets the data from cache and the ttl of data

func (*Cache) Set

func (c *Cache) Set(ctx context.Context, key string, value any, ttl ...time.Duration) error

Set marshals the value to bytes and sets to cache

func (*Cache) SetBytes

func (c *Cache) SetBytes(ctx context.Context, key string, value []byte, ttl ...time.Duration) error

SetBytes sets the data to cache

type CacheOption

type CacheOption func(opt *Option)

CacheOption cache option

func CacheCleanWindowOption

func CacheCleanWindowOption(cleanWindow time.Duration) CacheOption

CacheCleanWindowOption set clean window for bigcache store

func CacheCompressorOption

func CacheCompressorOption(compressor Compressor) CacheOption

CacheCompressorOption set compressor for store, the data will be compressed if matched

func CacheHardMaxCacheSizeOption

func CacheHardMaxCacheSizeOption(hardMaxCacheSize int) CacheOption

CacheHardMaxCacheSizeOption set hard max cache size for bigcache store

func CacheKeyPrefixOption

func CacheKeyPrefixOption(keyPrefix string) CacheOption

CacheKeyPrefixOption set key prefix for store

func CacheMaxEntrySizeOption

func CacheMaxEntrySizeOption(maxEntrySize int) CacheOption

CacheMaxEntrySizeOption set max entry size for bigcache store

func CacheMultiTTLOption added in v2.0.1

func CacheMultiTTLOption(ttlList []time.Duration) CacheOption

CacheMultiTTLOption set multi ttl for store

func CacheOnRemoveOption

func CacheOnRemoveOption(onRemove func(key string)) CacheOption

CacheOnRemoveOption set on remove function for bigcache store

func CacheSecondaryStoreOption

func CacheSecondaryStoreOption(store Store) CacheOption

CacheSecondaryStoreOption set secondary store for cache, it is slower with greater capacity

func CacheShardsOption

func CacheShardsOption(shards int) CacheOption

CacheShardsOption set shards for bigcache store

func CacheSnappyOption

func CacheSnappyOption(minCompressLength int) CacheOption

CacheSnappyOption set snappy compress for store

func CacheStoreOption

func CacheStoreOption(store Store) CacheOption

CacheStoreOption set custom store for cache, the bigcache store will be used as default

func CacheZSTDOption

func CacheZSTDOption(minCompressLength, level int) CacheOption

CacheZSTDOption set zstd compress for store

type Compressor

type Compressor interface {
	// Match tests the data should be compressed
	Match(size int) (matched bool)
	// Encode encodes the data
	Encode(data []byte) ([]byte, error)
	// Decode decodes the data
	Decode(data []byte) ([]byte, error)
}

Compressor is the interface that support encode and decode function for compression.

Match returns the size is matched for compress

func NewCompressor

func NewCompressor(opt CompressorOption) Compressor

NewCompressor creates a new compressor

func NewSnappyCompressor

func NewSnappyCompressor(minCompressLength int) Compressor

NewSnappyCompressor creates a snappy compressor

func NewZSTDCompressor

func NewZSTDCompressor(minCompressLength, level int) Compressor

NewZSTDCompressor creates a zstd compressor

type CompressorOption

type CompressorOption struct {
	// MinCompressLength min compress length
	MinCompressLength int
	// Encode encode function
	Encode func(data []byte) ([]byte, error)
	// Decode decode function
	Decode func(data []byte) ([]byte, error)
}

type Done

type Done func() error

Done done function

type Marshaler

type Marshaler interface {
	Marshal(v any) ([]byte, error)
}

type Option

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

type RedisCache

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

RedisCache redis cache

func NewRedisCache

func NewRedisCache(c redis.UniversalClient, opts ...RedisCacheOption) *RedisCache

NewRedisCache returns a new redis cache

func (*RedisCache) Del

func (c *RedisCache) Del(ctx context.Context, key string) (int64, error)

Del deletes data from cache

func (*RedisCache) Get

func (c *RedisCache) Get(ctx context.Context, key string) ([]byte, error)

Get gets value from cache

func (*RedisCache) GetAndDel

func (c *RedisCache) GetAndDel(ctx context.Context, key string) ([]byte, error)

GetAndDel gets value and deletes it remove cache

func (*RedisCache) GetIgnoreNilErr

func (c *RedisCache) GetIgnoreNilErr(ctx context.Context, key string) ([]byte, error)

GetIgnoreNilErr gets value from cache and ignore nil err

func (*RedisCache) GetStruct

func (c *RedisCache) GetStruct(ctx context.Context, key string, value any) error

GetStruct gets cache and unmarshal to struct

func (*RedisCache) GetStructAndTTL

func (c *RedisCache) GetStructAndTTL(ctx context.Context, key string, value any) (time.Duration, error)

GetStructAndTTL gets cache, unmarshal to struct and return the ttl of it. The cache should be set by SetStructWithTTL

func (*RedisCache) GetStructWithDone

func (c *RedisCache) GetStructWithDone(ctx context.Context, key string, value any) (Done, error)

GetStructWithDone gets data from redis and unmarshal to struct, it returns a done function to delete the data.

func (*RedisCache) IncWith

func (c *RedisCache) IncWith(ctx context.Context, key string, value int64, ttl ...time.Duration) (int64, error)

IncWith inc the value of key from cache

func (*RedisCache) Lock

func (c *RedisCache) Lock(ctx context.Context, key string, ttl ...time.Duration) (bool, error)

Lock the key for ttl, ii will return true, nil if success

func (*RedisCache) LockWithDone

func (c *RedisCache) LockWithDone(ctx context.Context, key string, ttl ...time.Duration) (bool, Done, error)

LockWithDone locks the key for ttl and return done function to delete the lock

func (*RedisCache) Set

func (c *RedisCache) Set(ctx context.Context, key string, value any, ttl ...time.Duration) error

Set sets data to cache, if ttl is not nil, it will use default ttl

func (*RedisCache) SetStruct

func (c *RedisCache) SetStruct(ctx context.Context, key string, value any, ttl ...time.Duration) error

SetStruct marshals struct to bytes and sets to cache, if it will use default ttl if ttl is nil

func (*RedisCache) SetStructWithTTL

func (c *RedisCache) SetStructWithTTL(ctx context.Context, key string, value any, ttl time.Duration) error

SetStructWithTTL adds expiredAt field to data, marshals data to bytes and sets to cache

func (*RedisCache) TTL

func (c *RedisCache) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the ttl of the key

type RedisCacheOption

type RedisCacheOption func(c *RedisCache)

RedisCacheOption redis cache option

func RedisCachePrefixOption

func RedisCachePrefixOption(prefix string) RedisCacheOption

func RedisCacheTTLOption

func RedisCacheTTLOption(ttl time.Duration) RedisCacheOption

type RedisSession

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

func NewRedisSession

func NewRedisSession(c redis.UniversalClient) *RedisSession

NewRedisSession returns a new redis session

func (*RedisSession) Destroy

func (rs *RedisSession) Destroy(ctx context.Context, key string) error

Destroy session from redis

func (*RedisSession) Get

func (rs *RedisSession) Get(ctx context.Context, key string) ([]byte, error)

Get session from redis, it will not return error if data is not exists

func (*RedisSession) Set

func (rs *RedisSession) Set(ctx context.Context, key string, data []byte, ttl time.Duration) error

Set session to redis

func (*RedisSession) SetPrefix

func (rs *RedisSession) SetPrefix(prefix string)

SetPrefix sets prefix for redis session's key

type Store

type Store interface {
	// Set sets data to store, the value should be copy before save to store
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
	// Get gets data from store
	Get(ctx context.Context, key string) ([]byte, error)
	// Delete deletes data form store
	Delete(ctx context.Context, key string) error
	// Close closes the store
	Close(ctx context.Context) error
}

Store interface for cache

func NewRedisStore

func NewRedisStore(client redis.UniversalClient) Store

type Unmarshaler

type Unmarshaler interface {
	Unmarshal(data []byte, value any) error
}

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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