feature: redis pool

This commit is contained in:
bryanqiu 2024-06-21 17:08:16 +08:00
parent 66a8d078a0
commit dcc42736da
3 changed files with 39 additions and 41 deletions

View File

@ -1,45 +1,11 @@
package redis
import (
"fmt"
"time"
"github.com/gomodule/redigo/redis"
"qoobing.com/gomod/redis/redis"
"qoobing.com/gomod/redis/sentinel"
)
func newSentinelPool() *redis.Pool {
sntnl := &sentinel.Sentinel{
Addrs: []string{":26379", ":26380", ":26381"},
MasterName: "mymaster",
Dial: func(addr string) (redis.Conn, error) {
timeout := 500 * time.Millisecond
c, err := redis.DialTimeout("tcp", addr, timeout, timeout, timeout)
if err != nil {
return nil, err
}
return c, nil
},
}
return &redis.Pool{
MaxIdle: 3,
MaxActive: 64,
Wait: true,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
masterAddr, err := sntnl.MasterAddr()
if err != nil {
return nil, err
}
c, err := redis.Dial("tcp", masterAddr)
if err != nil {
return nil, err
}
if !sentinel.TestRole(c, "master") {
c.Close()
return nil, fmt.Errorf("%s is not redis master", masterAddr)
}
return c, nil
},
}
}
type Config = sentinel.Config
var NewPool = redis.NewPool
var NewSentinelPool = sentinel.NewPool

View File

@ -36,3 +36,30 @@ func TestNewConsumer(t *testing.T) {
})
}
}
func TestNewPool(t *testing.T) {
cfg := Config{
Debug: true, //调试开关会在日志打印REDIS语句)
Master: "redis-0.redis:2379", //REDIS主
Username: "web3wallet", //REDIS连接用户名
Password: "web3onthemoon@2023#dev", //REDIS连接用户密码
Sentinels: "sentinel-0.redis:5000", //哨兵节点列表,逗号分隔,一般配置三个
SentinelUsername: "sentinel", //哨兵节点连接用户名不填默认default
SentinelPassword: "password@mhxzkhl#dev", //哨兵节点连接密码,不填认为集群无密码
}
pool := NewPool(cfg)
if pool == nil {
t.Errorf("new pool failed")
}
rds := pool.Get()
if rds == nil {
t.Errorf("get redis failed")
}
if ret, err := rds.Do("SET", "ABC", "123"); err != nil {
t.Errorf("get redis failed: %s", err)
} else {
fmt.Println("ABC", ret)
}
fmt.Println(rds.Do("GET", "ABC"))
}

View File

@ -16,7 +16,8 @@ import (
type Config struct {
Debug bool `toml:"debug"` //调试开关会在日志打印REDIS语句)
MasterName string `toml:"mastername"` //REDIS主名称一个哨兵集群可管理多个REDIS主从结构
Master string `toml:"mastername"` //REDIS主host&port 与 MasterName 互斥
MasterName string `toml:"mastername"` //REDIS主名称,值不为空是启动sentinal模式, 与Master互斥
Username string `toml:"username"` //REDIS连接用户名
Password string `toml:"password"` //REDIS连接用户密码
Sentinels string `toml:"sentinels"` //哨兵节点列表,逗号分隔,一般配置三个
@ -53,6 +54,11 @@ type Sentinel struct {
}
func NewPool(cfg Config) *redis.Pool {
if cfg.MasterName == "" {
panic("config is invalid: MasterName is empty")
} else if cfg.Master != "" && cfg.MasterName != "" {
//panic("config is invalid: Master & MasterName must not set both")
}
var (
masterName = cfg.MasterName
masterUsername = cfg.Username
@ -88,7 +94,6 @@ func NewPool(cfg Config) *redis.Pool {
cfg.Wait = new(bool)
*cfg.Wait = true
}
if cfg.IdleTimeout == nil {
cfg.IdleTimeout = new(int)
*cfg.IdleTimeout = 300