# cache **Repository Path**: aesoper/cache ## Basic Information - **Project Name**: cache - **Description**: 封装了redis+memcache的基础缓存功能,只需要修改一个简单的配置就可以快速的切换缓存方式,而无需再去写相关的代码。提供了可扩展的接口,方面开发者扩展其他的缓存类型,比如内存缓存。 - **Primary Language**: Go - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 4 - **Forks**: 2 - **Created**: 2020-05-19 - **Last Updated**: 2025-02-13 ## Categories & Tags **Categories**: cache-modules **Tags**: None ## README # 可切换使用的缓存驱动 ## 开发原由 在开发项目经常使用到redis、memcache、memory 等缓存,如果新手则不得不花时间去看各类文档,然后再编写各种缓存类型相关的代码。 且每个类型的配置以及api 千差万别,很让人头疼,于是便有了编写一个统一可扩展的缓存驱动的念头。受益于golang的sql/databases数据库驱动 开发思路的启发,于是便有了该项目 ## 特性 * 可配置 * 可扩展 ## 目前支持的缓存 * redis * memcache * memory ## 扩展接口 ```go Cache interface { Get(key string) ([]byte, error) Put(key string, val interface{}, timeout time.Duration) error Delete(key string) error Incr(key string) error Decr(key string) error IsExist(key string) bool ClearAll() error StartAndConfigure(ops ...CacheOption) error Close() error } ``` 如果您觉得提供的redis以及memcache缓存不能满足您的要求,可以根据以上接口编写自己的缓存驱动, 然后注册驱动到工厂就可以使用了 ```go func init() { factory.Register("redis", NewRedisCache) } ``` ## 如何使用 首先当然是先下载代码了 ``` go get -u gitee.com/aesoper/cache ``` ### 第一种方式 ```go cache, err := factory.NewCache("memcache") if err != nil { return } cache.Put("test", "111", time.Minute*5) cache.Put("test2", "2222", time.Minute*5) ``` ### 第二种方式 ```go c, err := cache.New(Cfg{ Driver: "redis", Redis: redis.Options{ Addr: "localhost:6379", }, }) if err != nil { return } c.Put("test", "111", time.Minute*5) ``` ### 注意事项 1. 如果使用memory,在使用Get返回的[]byte进行解码时建议使用`encoding/gob`包,否则有可能出先乱码 ## 开发依赖的第三方 1. [redis类库](https://github.com/go-redis/redis) 2. [memcache类库](https://github.com/bradfitz/gomemcache) 3. [测试类库](https://github.com/stretchr/testify) 4. [memory类库](https://github.com/patrickmn/go-cache) #### 参与贡献 1. Fork 本仓库 2. 新建 Feat_xxx 分支 3. 提交代码 4. 新建 Pull Request #### 码云特技 1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md 2. 码云官方博客 [blog.gitee.com](https://blog.gitee.com) 3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解码云上的优秀开源项目 4. [GVP](https://gitee.com/gvp) 全称是码云最有价值开源项目,是码云综合评定出的优秀开源项目 5. 码云官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) 6. 码云封面人物是一档用来展示码云会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)