-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
72 lines (66 loc) · 2.73 KB
/
redis.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package orm
import (
"context"
"crypto/tls"
"fmt"
"time"
"github.com/go-pay/xtime"
"github.com/redis/go-redis/v9"
)
// RedisConfig redis config.
type RedisConfig struct {
Addrs []string `json:"addrs" yaml:"addrs" toml:"addrs"`
Username string `json:"username" yaml:"username" toml:"username"`
Password string `json:"password" yaml:"password" toml:"password"`
DB int `json:"db" yaml:"db" toml:"db"`
ReadTimeout xtime.Duration `json:"read_timeout" yaml:"read_timeout" toml:"read_timeout"`
WriteTimeout xtime.Duration `json:"write_timeout" yaml:"write_timeout" toml:"write_timeout"`
PoolSize int `json:"pool_size" yaml:"pool_size" toml:"pool_size"`
MinIdleConn int `json:"min_idle_conn" yaml:"min_idle_conn" toml:"min_idle_conn"`
MaxIdleConn int `json:"max_idle_conn" yaml:"max_idle_conn" toml:"max_idle_conn"`
TLS bool `json:"tls" yaml:"tls" toml:"tls"`
TLSCfg *tls.Config `json:"-" yaml:"-" toml:"-"`
Limiter redis.Limiter `json:"-" yaml:"-" toml:"-"`
OnConnFunc func(ctx context.Context, cn *redis.Conn) error `json:"-" yaml:"-" toml:"-"`
}
func InitRedis(c *RedisConfig) (rd *redis.Client) {
opts := &redis.Options{
Addr: c.Addrs[0],
OnConnect: c.OnConnFunc,
Username: c.Username,
Password: c.Password,
DB: c.DB,
PoolSize: c.PoolSize,
ReadTimeout: time.Duration(c.ReadTimeout),
WriteTimeout: time.Duration(c.WriteTimeout),
MinIdleConns: c.MinIdleConn,
MaxIdleConns: c.MaxIdleConn,
TLSConfig: c.TLSCfg,
//DisableIndentity: true,
}
rd = redis.NewClient(opts)
_, err := rd.Ping(context.Background()).Result()
if err != nil {
panic(fmt.Sprintf("failed to connect redis error:%+v", err))
}
return rd
}
func InitRedisCluster(c *RedisConfig) (rc *redis.ClusterClient) {
opts := &redis.ClusterOptions{
Addrs: c.Addrs,
OnConnect: c.OnConnFunc,
Username: c.Username,
Password: c.Password,
PoolSize: c.PoolSize,
ReadTimeout: time.Duration(c.ReadTimeout),
WriteTimeout: time.Duration(c.WriteTimeout),
TLSConfig: c.TLSCfg,
//DisableIndentity: true,
}
rc = redis.NewClusterClient(opts)
_, err := rc.Ping(context.Background()).Result()
if err != nil {
panic(fmt.Sprintf("failed to connect redis error:%+v", err))
}
return rc
}