2 Star 1 Fork 1

mosache / YFrame

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
redis.go 1.33 KB
一键复制 编辑 原始数据 按行查看 历史
ヤ沒脩袮兲︶ 提交于 2022-09-20 15:37 . init
package redis
import (
"errors"
"fmt"
"gitee.com/mosache/YFrame/util/ctx"
red "github.com/gomodule/redigo/redis"
"strings"
"time"
)
var (
pool *red.Pool
)
func InitRedis(conf *Config) error {
redisDialOpts := make([]red.DialOption, 0)
redisDialOpts = append(redisDialOpts, red.DialDatabase(conf.DB))
if len(strings.TrimSpace(conf.Password)) > 0 {
//redisDialOpts = append(redisDialOpts, red.DialUsername(conf.UserName))
redisDialOpts = append(redisDialOpts, red.DialPassword(conf.Password))
}
pool = &red.Pool{
Dial: func() (red.Conn, error) {
return red.Dial("tcp", fmt.Sprintf("%s:%d",
conf.Host, conf.Port),
redisDialOpts...)
},
MaxIdle: 100,
MaxActive: 500,
IdleTimeout: 20 * time.Second,
MaxConnLifetime: 60 * time.Second,
TestOnBorrow: func(c red.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
}
if pool == nil {
return errors.New("init redis error")
}
return ping()
}
func Close() error {
if pool != nil {
pool.Close()
}
return nil
}
func ping() error {
conn, err := pool.GetContext(ctx.WithTimeOut(5 * time.Second).Ctx)
if err != nil {
return err
}
r, err := red.String(conn.Do("PING"))
if err != nil {
return err
}
if r != "PONG" {
return errors.New("ping err")
}
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/mosache/YFrame.git
git@gitee.com:mosache/YFrame.git
mosache
YFrame
YFrame
v0.1.76

搜索帮助

344bd9b3 5694891 D2dac590 5694891