# cache **Repository Path**: nrgo/cache ## Basic Information - **Project Name**: cache - **Description**: cache interface & builtin cache provider (in process memory) for nrgo - **Primary Language**: Go - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-02-19 - **Last Updated**: 2023-04-03 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # cache #### 介绍 cache interface & builtin cache provider (in process memory) for nrgo #### 接口定义 ```go // Cache KV型缓存通用接口 type Cache interface { // Open 打开Cache服务 Open() error // Close 关闭Cache服务 Close() error // Set 设置指定kv到缓存中,如存在key则覆盖 Set(key string, value interface{}, expires ...time.Duration) // Get 获取指定key的value值 Get(key string) (interface{}, error) // Exists 查询缓存中是否存在指定key Exists(key string) bool // Expires 设置某个key的超时设置 Expires(key string, expires time.Duration) // Delete 从缓存中移除某个key Delete(key string) // Keys 返回缓存中的所有key Keys() []string // Size 返回缓存大小 Size() int } ``` #### 使用说明 ##### 常量说明 ```go // 错误定义 ErrKeyNotExists = errors.New(`key does not exist in the cache`) ErrKeyExpired = errors.New(`cache has expired`) // 配置参数定义 const ( // OPTIONS_DEFAULT_EXPIRES_NAME 默认过期时间配置名称,值类型为 time.Duration,默认值为 40分钟 OPTIONS_DEFAULT_EXPIRES_NAME = `expires` // OPTIONS_DEFAULT_CAPACITY_NAME 默认缓存集合大小,值类型为 int,默认值为 1000 OPTIONS_DEFAULT_CAPACITY_NAME = `capacity` ) ``` ##### 使用说明 ```go // 默认初始化 bc := NewBuiltinCache() // 带参数初始化 bc := NewBuiltinCache( options.WithOption(OPTIONS_DEFAULT_CAPACITY_NAME, 6), options.WithOption(OPTIONS_DEFAULT_EXPIRES_NAME, time.Second*2), ) // 开启缓存 bc.Open() // 设置缓存 bc.Set("string", "string") bc.Set("int64", int64(123)) // 获取值 v, e := bc.Get("string") // v:string e:nil v, e := bc.Get("not exists") // v:nil e:ErrKeyNotExists // 缓存数量 size := bc.Size() keys := bc.Keys() len(size) // 2 len(keys) // 2 // 设置单缓存超时 bc.Set("string", "string2", time.Second) bc.Expires("string", time.Second) // 关闭缓存 bc.Close() ```