文章目录
Redis 参考文档
本文件介绍如何利用Gone内置模块,操作redis,包括使用分布式缓存、分布式锁、操作键值、操作Hash等内容,是对Gone框架介绍18 - redis 分布式缓存 和 分布式锁 的补充和完善。
已经收录到官方文档:https://goner.fun/zh/references/redis.html
配置项
- redis.max-idle:最大空闲链接数,不配置默认为2
- redis.max-active:最大活跃链接数,不配置默认为10
- redis.db:使用的db,不配置默认为0
- redis.cache.prefix:key前缀,如果设置了,对redis的增删改查都会拼接该前缀,拼接方式KaTeX parse error: Expected 'EOF', got '#' at position 9: {prefix}#̲{key};默认为空
import 和 bury
- import
import "github.com/gone-io/gone/goner/redis"
- bury
//使用 goner.RedisPriest 函数,将 redis 相关的Goner 埋葬到 Cemetery 中
_ = goner.RedisPriest(cemetery)
使用分布是缓存 redis.Cache
接口定义
type Cache interface {
//设置缓存,Set的别名
Put(key string, value any, ttl ...time.Duration) error
//设置缓存
Set(key string, value any, ttl ...time.Duration) error
//获取缓存
Get(key string, value any) error
//删除缓存
Remove(key string) (err error)
//根据模式获取缓存的key
Keys(pattern string) ([]string, error)
//获取当前Cache使用的前缀
Prefix() string
}
使用示例
type redisUser struct {
gone.Flag
cache redis.Cache `gone:"gone-redis-cache"`
}
func (r *redisUser) UseCache() {
key := "gone-address"
value := "https://github.com/gone-io/gone"
//设置缓存
err := r.cache.Put(
key, //第一个参数为 缓存的key,类型为 `string`
value, // 第二参数为 需要缓存的值,类型为any,可以是任意类型;传入的值会被编码为 `[]byte` 发往redis
10*time.Second, // 第三个参数为 过期时间,类型为 `time.Duration`;省略,表示不设置过期时间