2025年3月25日 星期二 甲辰(龙)年 月廿四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Go语言

gookit/cache 基于 Golang 通用的缓存管理使用库

时间:12-14来源:作者:点击数:2

Golang 通用的缓存管理使用库。 通过包装各种常用的驱动,屏蔽掉底层各个驱动的不同使用方法,来提供统一的使用API。

所有缓存驱动程序都实现了 cache.Cache 接口。 因此,您可以添加任何自定义驱动程序。

支持的驱动

内部实现

  • file 简单的文件缓(当前包的内置实现
  • memory 简单的内存缓存(当前包的内置实现

安装

  • go get github.com/gookit/cache

接口方法

所有缓存驱动程序都实现了cache.Cache接口。 因此,您可以添加任何自定义驱动程序。

  • // Cache interface definition
  • type Cache interface {
  • // basic op
  • Has(key string) bool
  • Get(key string) interface{}
  • Set(key string, val interface{}, ttl time.Duration) (err error)
  • Del(key string) error
  • // multi op
  • GetMulti(keys []string) map[string]interface{}
  • SetMulti(values map[string]interface{}, ttl time.Duration) (err error)
  • DelMulti(keys []string) error
  • // clear
  • Clear() error
  • }

使用

  • package main
  • import (
  • "fmt"
  • "github.com/gookit/cache"
  • "github.com/gookit/cache/goredis"
  • "github.com/gookit/cache/redis"
  • )
  • func main() {
  • // 注册一个(或多个)缓存驱动
  • cache.Register(cache.DvrFile, cache.NewFileCache(""))
  • cache.Register(cache.DvrMemory, cache.NewMemoryCache())
  • cache.Register(redis.Name, redis.Connect("127.0.0.1:6379", "", 0))
  • cache.Register(goredis.Name, goredis.Connect("127.0.0.1:6379", "", 0))
  • // 设置默认驱动名称
  • cache.DefaultUse(cache.DvrRedis)
  • // 快速使用(默认驱动)
  • //
  • // set
  • cache.Set("name", "cache value", cache.TwoMinutes)
  • // get
  • val := cache.Get("name")
  • // del
  • cache.Del("name")
  • // Out: "cache value"
  • fmt.Print(val)
  • // 使用已注册的其他驱动
  • client := cache.Driver(cache.DvrFile)
  • client.Set("key", "val", 0)
  • val = client.Get("key")
  • // Out: "val"
  • fmt.Print(val)
  • }

设置选项

  • gords := goredis.Connect("127.0.0.1:6379", "", 0)
  • gords.WithOptions(cache.WithPrefix("cache_"), cache.WithEncode(true))
  • cache.Register(goredis.Name, gords)
  • // set
  • // real key is: "cache_name"
  • cache.Set("name", "cache value", cache.TwoMinutes)
  • // get: "cache value"
  • val := cache.Get("name")

github 地址:https://github.com/gookit/cache

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐