GIN框架初始化Redis
GIN Redis
·
问题:gin框架并没有将redis封装,如果每次使用redis都进行链接,过于耗费资源,所以将redis加入初始化中,需要用redis时,直接引入变量即可。
安装
go get -u github.com/go-redis/redis/v8
定义配置项
type Redis struct {
Host string
Password string
DB int
IdleTimeout time.Duration
}
config.yaml 中添加对应配置
redis:
host: 127.0.0.1:6379
db: 0
password:
初始化redis
package redis
import (
"context"
"time"
"github.com/go-redis/redis/v8"
"global"
)
var (
MyRedis *redis.Client
ctx = context.Background()
)
func Setup() {
MyRedis = redis.NewClient(&redis.Options{
Addr: global.App.Config.Redis.Host,
Password: global.App.Config.Redis.Password, // no password set
DB: global.App.Config.Redis.DB, // use default DB
})
_, err := MyRedis.Ping(ctx).Result()
if err != nil {
logging.Error("Redis connect ping failed, err:", err)
return
}
logging.Error("Redis connect succeeded")
return
}
这里如果没有global的话,只要能拿到数据参数也是可以的。
在 main.go 的 init 中 调用Setup
package main
func init() {
......
// redis 初始化
redis.Setup()
}
封装Redis方法
package redis
var (
MyRedis *redis.Client
ctx = context.Background()
)
func Setup() {
MyRedis = redis.NewClient(&redis.Options{
Addr: global.App.Config.Redis.Host,
Password: global.App.Config.Redis.Password, // no password set
DB: global.App.Config.Redis.DB, // use default DB
})
_, err := MyRedis.Ping(context.Background()).Result()
if err != nil {
logging.Error("Redis connect ping failed, err:", err)
return
}
logging.Error("Redis connect succeeded")
return
}
func SetRedis(key string, value string, t int64) bool {
expire := time.Duration(t) * time.Second
if err := MyRedis.Set(ctx, key, value, expire).Err(); err != nil {
return false
}
return true
}
func GetRedis(key string) string {
result, err := MyRedis.Get(ctx, key).Result()
if err != nil {
return ""
}
return result
}
func DelRedis(key string) bool {
_, err := MyRedis.Del(ctx, key).Result()
if err != nil {
fmt.Println(err)
return false
}
return true
}
func ExpireRedis(key string, t int64) bool {
// 延长过期时间
expire := time.Duration(t) * time.Second
if err := MyRedis.Expire(ctx, key, expire).Err(); err != nil {
fmt.Println(err)
return false
}
return true
}
更多推荐
已为社区贡献1条内容
所有评论(0)