gocache

gocache

Go语言多功能缓存库gocache支持多种存储和高级特性

gocache是一个功能全面的Go缓存库,支持内存、Redis等多种存储后端。它提供链式缓存、可加载缓存、指标统计等高级特性,并支持标签失效。gocache采用泛型设计,支持自动序列化,易于扩展自定义存储。这个库为开发者提供了灵活而高效的缓存解决方案。

Go缓存库多存储支持链式缓存可加载缓存缓存失效Github开源项目

测试 GoDoc GoReportCard codecov

Gocache

猜猜Gocache是什么?一个Go缓存库。 这是一个可扩展的缓存库,为您提供了许多缓存数据的功能。

概述

以下是它具体提供的功能:

  • ✅ 多种缓存存储:实际上包括内存、redis或您自己的自定义存储
  • ✅ 链式缓存:按优先顺序使用多个缓存(例如先使用内存,然后回退到redis共享缓存)
  • ✅ 可加载缓存:允许您调用回调函数将数据重新放入缓存
  • ✅ 指标缓存,让您存储有关缓存使用情况的指标(命中、未命中、设置成功、设置错误等)
  • ✅ 自动对缓存值进行结构体的编组/解组的编组器
  • ✅ 在存储中定义默认值,并在设置数据时覆盖它们
  • ✅ 通过过期时间和/或使用标签进行缓存失效
  • ✅ 使用泛型

内置存储

内置指标提供者

安装

要开始使用最新版本的gocache,您可以在项目中导入该库:

go get github.com/eko/gocache/lib/v4

然后,在所有可用的存储中导入您想要使用的存储:

go get github.com/eko/gocache/store/bigcache/v4 go get github.com/eko/gocache/store/freecache/v4 go get github.com/eko/gocache/store/go_cache/v4 go get github.com/eko/gocache/store/hazelcast/v4 go get github.com/eko/gocache/store/memcache/v4 go get github.com/eko/gocache/store/pegasus/v4 go get github.com/eko/gocache/store/redis/v4 go get github.com/eko/gocache/store/rediscluster/v4 go get github.com/eko/gocache/store/rueidis/v4 go get github.com/eko/gocache/store/ristretto/v4

然后,简单地使用以下导入语句:

import ( "github.com/eko/gocache/lib/v4/cache" "github.com/eko/gocache/store/redis/v4" )

如果遇到任何错误,请确保运行go mod tidy来清理您的go.mod文件。

详细的可用缓存功能

简单缓存

这里是使用Redis的简单缓存实例化,但您也可以查看其他可用的存储:

Memcache

memcacheStore := memcache_store.NewMemcache( memcache.New("10.0.0.1:11211", "10.0.0.2:11211", "10.0.0.3:11212"), store.WithExpiration(10*time.Second), ) cacheManager := cache.New[[]byte](memcacheStore) err := cacheManager.Set(ctx, "my-key", []byte("my-value"), store.WithExpiration(15*time.Second), // 覆盖存储中定义的10秒默认值 ) if err != nil { panic(err) } value := cacheManager.Get(ctx, "my-key") cacheManager.Delete(ctx, "my-key") cacheManager.Clear(ctx) // 清除整个缓存,以防您想刷新所有缓存

内存 (使用 Bigcache)

bigcacheClient, _ := bigcache.NewBigCache(bigcache.DefaultConfig(5 * time.Minute)) bigcacheStore := bigcache_store.NewBigcache(bigcacheClient) cacheManager := cache.New[[]byte](bigcacheStore) err := cacheManager.Set(ctx, "my-key", []byte("my-value")) if err != nil { panic(err) } value := cacheManager.Get(ctx, "my-key")

内存 (使用 Ristretto)

import ( "github.com/dgraph-io/ristretto" "github.com/eko/gocache/lib/v4/cache" "github.com/eko/gocache/lib/v4/store" ristretto_store "github.com/eko/gocache/store/ristretto/v4" ) ristrettoCache, err := ristretto.NewCache(&ristretto.Config{ NumCounters: 1000, MaxCost: 100, BufferItems: 64, }) if err != nil { panic(err) } ristrettoStore := ristretto_store.NewRistretto(ristrettoCache) cacheManager := cache.New[string](ristrettoStore) err := cacheManager.Set(ctx, "my-key", "my-value", store.WithCost(2)) if err != nil { panic(err) } value := cacheManager.Get(ctx, "my-key") cacheManager.Delete(ctx, "my-key")

内存 (使用 Go-cache)

gocacheClient := gocache.New(5*time.Minute, 10*time.Minute) gocacheStore := gocache_store.NewGoCache(gocacheClient) cacheManager := cache.New[[]byte](gocacheStore) err := cacheManager.Set(ctx, "my-key", []byte("my-value")) if err != nil { panic(err) } value, err := cacheManager.Get(ctx, "my-key") if err != nil { panic(err) } fmt.Printf("%s", value)

Redis

redisStore := redis_store.NewRedis(redis.NewClient(&redis.Options{ Addr: "127.0.0.1:6379", })) cacheManager := cache.New[string](redisStore) err := cacheManager.Set(ctx, "my-key", "my-value", store.WithExpiration(15*time.Second)) if err != nil { panic(err) } value, err := cacheManager.Get(ctx, "my-key") switch err { case nil: fmt.Printf("从redis缓存中获取键'%s'。结果:%s", "my-key", value) case redis.Nil: fmt.Printf("未能从redis缓存中找到键'%s'。", "my-key") default: fmt.Printf("未能从redis缓存中获取键'%s'的值:%v", "my-key", err) }

Redis客户端侧缓存 (使用 rueidis)

client, err := rueidis.NewClient(rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}}) if err != nil { panic(err) } cacheManager := cache.New[string](rueidis_store.NewRueidis( client, store.WithExpiration(15*time.Second), store.WithClientSideCaching(15*time.Second)), ) if err = cacheManager.Set(ctx, "my-key", "my-value"); err != nil { panic(err) } value, err := cacheManager.Get(ctx, "my-key") if err != nil { log.Fatalf("未能从redis缓存中获取键'%s'的值:%v", "my-key", err) } log.Printf("从redis缓存中获取键'%s'。结果:%s", "my-key", value)

Freecache

freecacheStore := freecache_store.NewFreecache(freecache.NewCache(1000), store.WithExpiration(10 * time.Second)) cacheManager := cache.New[[]byte](freecacheStore) err := cacheManager.Set(ctx, "by-key", []byte("my-value"), opts) if err != nil { panic(err) } value := cacheManager.Get(ctx, "my-key")

Pegasus

pegasusStore, err := pegasus_store.NewPegasus(&store.OptionsPegasus{ MetaServers: []string{"127.0.0.1:34601", "127.0.0.1:34602", "127.0.0.1:34603"}, }) if err != nil { fmt.Println(err) return } cacheManager := cache.New[string](pegasusStore) err = cacheManager.Set(ctx, "my-key", "my-value", store.WithExpiration(10 * time.Second)) if err != nil { panic(err) } value, _ := cacheManager.Get(ctx, "my-key")

Hazelcast

hzClient, err := hazelcast.StartNewClient(ctx) if err != nil { log.Fatalf("启动客户端失败:%v", err) } hzMap, err := hzClient.GetMap(ctx, "gocache") if err != nil { b.Fatalf("获取地图失败:%v", err) } hazelcastStore := hazelcast_store.NewHazelcast(hzMap) cacheManager := cache.New[string](hazelcastStore) err := cacheManager.Set(ctx, "my-key", "my-value", store.WithExpiration(15*time.Second)) if err != nil { panic(err) } value, err := cacheManager.Get(ctx, "my-key") if err != nil { panic(err) } fmt.Printf("从hazelcast缓存中获取键'%s'。结果:%s", "my-key", value)

链式缓存

在这里,我们将按以下顺序链接缓存:首先使用Ristretto存储在内存中,然后使用Redis(作为后备):

// 初始化Ristretto缓存和Redis客户端 ristrettoCache, err := ristretto.NewCache(&ristretto.Config{NumCounters: 1000, MaxCost: 100, BufferItems: 64}) if err != nil { panic(err) } redisClient := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"}) // 初始化存储 ristrettoStore := ristretto_store.NewRistretto(ristrettoCache) redisStore := redis_store.NewRedis(redisClient, store.WithExpiration(5*time.Second)) // 初始化链式缓存 cacheManager := cache.NewChain[any]( cache.New[any](ristrettoStore), cache.New[any](redisStore), ) // ... 然后,用你的缓存做你想做的事

Chain缓存在找到数据时也会将数据放回之前的缓存中,所以在这种情况下,如果ristretto在其缓存中没有数据但redis有,数据也会被设置回ristretto(内存)缓存中。

可加载缓存

这个缓存将提供一个加载函数,作为可调用函数,在数据不可用时将数据重新设置到缓存中:

type Book struct { ID string Name string } // 初始化 Redis 客户端和存储 redisClient := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"}) redisStore := redis_store.NewRedis(redisClient) // 初始化一个从自定义源加载数据的函数 loadFunction := func(ctx context.Context, key any) (*Book, error) { // ... 从可用源检索值 return &Book{ID: 1, Name: "我的测试精彩图书"}, nil } // 初始化可加载缓存 cacheManager := cache.NewLoadable[*Book]( loadFunction, cache.New[*Book](redisStore), ) // ... 然后,你可以获取你的数据,你的函数将自动将它们放入缓存中

当然,你也可以将Chain缓存传递给Loadable缓存,这样如果你的数据在所有缓存中都不可用,它会将数据带回所有缓存中。

用于检索缓存统计信息的度量缓存

这个缓存将根据你传递给它的度量提供者记录度量。这里我们给出一个Prometheus提供者:

// 初始化 Redis 客户端和存储 redisClient := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"}) redisStore := redis_store.NewRedis(redisClient) // 初始化Prometheus度量服务 promMetrics := metrics.NewPrometheus("my-test-app") // 初始化度量缓存 cacheManager := cache.NewMetric[any]( promMetrics, cache.New[any](redisStore), ) // ... 然后,你可以获取你的数据,度量将被Prometheus观察

一个编组器包装器

一些缓存如Redis存储和返回值为字符串,所以如果你想缓存一个对象,你必须编组/解组你的结构体。这就是为什么我们提供了一个编组器服务,它包装你的缓存并为你完成这项工作:

// 初始化 Redis 客户端和存储 redisClient := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"}) redisStore := redis_store.NewRedis(redisClient) // 初始化链式缓存 cacheManager := cache.NewMetric[any]( promMetrics, cache.New[any](redisStore), ) // 初始化编组器 marshal := marshaler.New(cacheManager) key := BookQuery{Slug: "my-test-amazing-book"} value := Book{ID: 1, Name: "我的测试精彩图书", Slug: "my-test-amazing-book"} err = marshal.Set(ctx, key, value) if err != nil { panic(err) } returnedValue, err := marshal.Get(ctx, key, new(Book)) if err != nil { panic(err) } // 然后,对返回的值进行你想要的操作 marshal.Delete(ctx, "my-key")

你唯一需要做的是在调用.Get()方法时指定你想要将值解组到的结构体作为第二个参数。

使用标签进行缓存失效

你可以为创建的项目附加一些标签,以便以后轻松地使其失效。

标签使用与你为缓存选择的相同存储进行存储。

以下是如何使用它的示例:

// 初始化 Redis 客户端和存储 redisClient := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"}) redisStore := redis_store.NewRedis(redisClient) // 初始化链式缓存 cacheManager := cache.NewMetric[*Book]( promMetrics, cache.New[*Book](redisStore), ) // 初始化编组器 marshal := marshaler.New(cacheManager) key := BookQuery{Slug: "my-test-amazing-book"} value := &Book{ID: 1, Name: "我的测试精彩图书", Slug: "my-test-amazing-book"} // 在缓存中设置一个项目并附加一个"book"标签 err = marshal.Set(ctx, key, value, store.WithTags([]string{"book"})) if err != nil { panic(err) } // 删除所有具有"book"标签的项目 err := marshal.Invalidate(ctx, store.WithInvalidateTags([]string{"book"})) if err != nil { panic(err) } returnedValue, err := marshal.Get(ctx, key, new(Book)) if err != nil { // 应该被触发,因为项目已被删除,所以无法找到。 panic(err) }

将此与缓存的过期时间结合使用,以对你的数据如何被缓存进行精细控制。

package main import ( "fmt" "log" "time" "github.com/eko/gocache/lib/v4/cache" "github.com/eko/gocache/lib/v4/store" "github.com/redis/go-redis/v9" ) func main() { redisStore := redis_store.NewRedis(redis.NewClient(&redis.Options{ Addr: "127.0.0.1:6379", }), nil) cacheManager := cache.New[string](redisStore) err := cacheManager.Set(ctx, "my-key", "my-value", store.WithExpiration(15*time.Second)) if err != nil { panic(err) } key := "my-key" value, err := cacheManager.Get(ctx, key) if err != nil { log.Fatalf("无法从缓存中获取缓存键 '%s':%v", key, err) } fmt.Printf("%#+v\n", value) }

编写你自己的自定义缓存

缓存遵循以下接口,因此你可以通过实现以下接口来编写自己的(专有?)缓存逻辑:

type CacheInterface[T any] interface { Get(ctx context.Context, key any) (T, error) Set(ctx context.Context, key any, object T, options ...store.Option) error Delete(ctx context.Context, key any) error Invalidate(ctx context.Context, options ...store.InvalidateOption) error Clear(ctx context.Context) error GetType() string }

或者,如果你使用setter缓存,还要实现GetCodec()方法:

type SetterCacheInterface[T any] interface { CacheInterface[T] GetWithTTL(ctx context.Context, key any) (T, time.Duration, error) GetCodec() codec.CodecInterface }

由于此库中的所有缓存都实现了CacheInterface,你将能够将自己的缓存与你自己的缓存混合使用。

编写你自己的自定义存储

你还可以通过实现以下接口来编写自己的自定义存储:

type StoreInterface interface { Get(ctx context.Context, key any) (any, error) GetWithTTL(ctx context.Context, key any) (any, time.Duration, error) Set(ctx context.Context, key any, value any, options ...Option) error Delete(ctx context.Context, key any) error Invalidate(ctx context.Context, options ...InvalidateOption) error Clear(ctx context.Context) error GetType() string }

当然,我建议你看看当前的缓存或存储来实现你自己的。

自定义缓存键生成器

你可以实现以下接口来生成自定义缓存键:

type CacheKeyGenerator interface { GetCacheKey() string }

基准测试

基准测试

运行测试

要使用mockgen库生成模拟,请运行:

$ make mocks

测试套件可以通过以下方式运行:

$ make test # 运行单元测试

社区

请随时为这个库做出贡献,如果你想讨论某个功能,请不要犹豫,直接开一个issue。

编辑推荐精选

扣子-AI办公

扣子-AI办公

职场AI,就用扣子

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成AI工具AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机AI图像热门
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

下拉加载更多