一个基于 bigcache 的 Go 缓存库,提供了更丰富的缓存操作接口。
- 支持设置缓存过期时间
- 支持字符串和字节数组存储
- 提供计数器操作(递增/递减)
- 线程安全
- 自动清理过期数据
go get github.com/leafney/rose-cache// 创建一个默认10分钟过期的缓存实例cache, err:=rcache.NewCache(10)
iferr!=nil {
log.Fatal(err)
}
defercache.Close()
// 存储数据err=cache.XSetEx("key", []byte("value"), 5time.Minute)
// 获取数据val, err:=cache.XGet("key")设置缓存中条目的有效期。超过此时间后,条目将自动从缓存中删除。
设置缓存的清理间隔。每隔此时间段后,缓存会自动检查并删除过期的条目,以保持最佳性能和内存使用。
例如:设置为 10 分钟,则每隔 10 分钟会进行一次过期数据的清理操作。
允许为 BigCache 实例设置自定义上下文,用于控制缓存的生命周期。
// 创建新的缓存实例funcNewCache(minuteint64, opts...Option) (*Cache, error)
// 关闭缓存并释放资源func (c*Cache) Close() error// 检查键是否存在func (c*Cache) Exists(keystring) bool// 删除指定键的缓存项func (c*Cache) Del(keystring) error// 设置缓存键值对func (c*Cache) Set(keystring, value []byte) errorfunc (c*Cache) SetS(keystring, valuestring) error// 获取缓存值func (c*Cache) Get(keystring) ([]byte, error)
func (c*Cache) GetS(keystring) (string, error)// 存储数据(支持过期时间)func (c*Cache) XSet(keystring, value []byte) errorfunc (c*Cache) XSetS(keystring, valuestring) errorfunc (c*Cache) XSetEx(keystring, value []byte, expires time.Duration) errorfunc (c*Cache) XSetExS(keystring, valuestring, expires time.Duration) errorfunc (c*Cache) XSetExSec(keystring, value []byte, secondsint64) errorfunc (c*Cache) XSetExSecS(keystring, valuestring, secondsint64) error// 获取数据func (c*Cache) XGet(keystring) ([]byte, error)
func (c*Cache) XGetS(keystring) (string, error)// 设置过期时间func (c*Cache) XExpireAt(keystring, tm time.Time) errorfunc (c*Cache) XExpire(keystring, expires time.Duration) errorfunc (c*Cache) XExpireSec(keystring, secondsint64) error// 获取剩余生存时间(秒)func (c*Cache) XTTL(keystring) (int64, error)// 递增操作func (c*Cache) XIncr(keystring) (int64, error)
func (c*Cache) XIncrBy(keystring, incrementint64) (int64, error)
// 递减操作func (c*Cache) XDecr(keystring) (int64, error)
func (c*Cache) XDecrBy(keystring, decrementint64) (int64, error)WithLifeWindow-- 用来设置缓存的生命周期时长。WithCleanWindow-- 用来设置缓存过期后多久被清除的时间,超过该时间,所有过期的条目会被删除,仍在有效期内的条目不会被删除。
库定义了以下错误类型:
var (
ErrKeyEmpty=errors.New("key is empty")
ErrKeyNotFound=errors.New("key not found")
ErrValueEmpty=errors.New("value is empty")
ErrNilCache=errors.New("cache is nil")
)