🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] > [github](https://github.com/eko/gocache) ## 概述 - 多个缓存存储:实际上在内存,Redis或您自己的自定义存储中 - 链式缓存:以优先级顺序使用多个缓存(例如,内存然后回退到Redis共享缓存) - 可加载的缓存:允许您调用回调函数以将数据放回缓存 - 指标缓存,用于存储有关缓存使用情况的指标(命中,未命中,设置成功,设置错误等) - 封送处理程序可自动封送/解组缓存值作为结构 - 在商店中定义默认值,并在设置数据时覆盖它们 - 通过到期时间和/或使用标签来使缓存无效 ### 内置缓存 * [Memory (bigcache)](https://github.com/allegro/bigcache)(allegro/bigcache) * [Memory (ristretto)](https://github.com/dgraph-io/ristretto)(dgraph-io/ristretto) * [Memcache](https://github.com/bradfitz/gomemcache)(bradfitz/memcache) * [Redis](https://github.com/go-redis/redis/v7)(go-redis/redis) * More to come soon ## 例子 ### memched ``` memcacheStore := store.NewMemcache( memcache.New("10.0.0.1:11211", "10.0.0.2:11211", "10.0.0.3:11212"), &store.Options{ Expiration: 10*time.Second, }, ) cacheManager := cache.New(memcacheStore) err := cacheManager.Set("my-key", []byte("my-value"), &cache.Options{ Expiration: 15*time.Second, // Override default value of 10 seconds defined in the store }) if err != nil { panic(err) } value := cacheManager.Get("my-key") cacheManager.Delete("my-key") cacheManager.Clear() // Clears the entire cache, in case you want to flush all cache ``` ### Memory (using Bigcache) ``` bigcacheClient, _ := bigcache.NewBigCache(bigcache.DefaultConfig(5 * time.Minute)) bigcacheStore := store.NewBigcache(bigcacheClient, nil) // No otions provided (as second argument) cacheManager := cache.New(bigcacheStore) err := cacheManager.Set("my-key", "my-value", nil) if err != nil { panic(err) } value := cacheManager.Get("my-key") ``` ### Memory (using Ristretto) ``` ristrettoCache, err := ristretto.NewCache(&ristretto.Config{ NumCounters: 1000, MaxCost: 100, BufferItems: 64, }) if err != nil { panic(err) } ristrettoStore := store.NewRistretto(ristrettoCache, nil) cacheManager := cache.New(ristrettoStore) err := cacheManager.Set("my-key", "my-value", &cache.Options{Cost: 2}) if err != nil { panic(err) } value := cacheManager.Get("my-key") cacheManager.Delete("my-key") ``` ### Redis ``` redisStore := store.NewRedis(redis.NewClient(&redis.Options{ Addr: "127.0.0.1:6379", }), nil) cacheManager := cache.New(redisStore) err := cacheManager.Set("my-key", "my-value", &cache.Options{Expiration: 15*time.Second}) if err != nil { panic(err) } value := cacheManager.Get("my-key") ```