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。

编辑推荐精选

QoderWork

QoderWork

阿里Qoder团队推出的桌面端AI智能体

QoderWork 是阿里推出的本地优先桌面 AI 智能体,适配 macOS14+/Windows10+,以自然语言交互实现文件管理、数据分析、AI 视觉生成、浏览器自动化等办公任务,自主拆解执行复杂工作流,数据本地运行零上传,技能市场可无限扩展,是高效的 Agentic 生产力办公助手。

音述AI

音述AI

全球首个AI音乐社区

音述AI是全球首个AI音乐社区,致力让每个人都能用音乐表达自我。音述AI提供零门槛AI创作工具,独创GETI法则帮助用户精准定义音乐风格,AI润色功能支持自动优化作品质感。音述AI支持交流讨论、二次创作与价值变现。针对中文用户的语言习惯与文化背景进行专门优化,支持国风融合、C-pop等本土音乐标签,让技术更好地承载人文表达。

lynote.ai

lynote.ai

一站式搞定所有学习需求

不再被海量信息淹没,开始真正理解知识。Lynote 可摘要 YouTube 视频、PDF、文章等内容。即时创建笔记,检测 AI 内容并下载资料,将您的学习效率提升 10 倍。

AniShort

AniShort

为AI短剧协作而生

专为AI短剧协作而生的AniShort正式发布,深度重构AI短剧全流程生产模式,整合创意策划、制作执行、实时协作、在线审片、资产复用等全链路功能,独创无限画布、双轨并行工业化工作流与Ani智能体助手,集成多款主流AI大模型,破解素材零散、版本混乱、沟通低效等行业痛点,助力3人团队效率提升800%,打造标准化、可追溯的AI短剧量产体系,是AI短剧团队协同创作、提升制作效率的核心工具。

seedancetwo2.0

seedancetwo2.0

能听懂你表达的视频模型

Seedance two是基于seedance2.0的中国大模型,支持图像、视频、音频、文本四种模态输入,表达方式更丰富,生成也更可控。

nano-banana纳米香蕉中文站

nano-banana纳米香蕉中文站

国内直接访问,限时3折

输入简单文字,生成想要的图片,纳米香蕉中文站基于 Google 模型的 AI 图片生成网站,支持文字生图、图生图。官网价格限时3折活动

扣子-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工具

下拉加载更多