gitee.com/h79/goutils@v1.22.10/dao/redis/pool/pool.go (about) 1 package pool 2 3 import ( 4 "fmt" 5 "gitee.com/h79/goutils/dao/config" 6 "time" 7 8 "github.com/go-redis/redis/v8" 9 ) 10 11 // Pool redis机群单例 12 var pool *Client 13 14 // Client 线程池类型 15 type Client struct { 16 Clusters []*redis.ClusterClient //集群 17 W int //写成功数 18 R int //读成功数 19 WriteTimeout time.Duration //总写时延 20 ReadTimeout time.Duration //总读时延 21 } 22 23 func NewPool(clusterConf []*config.Cluster) { 24 pool = newClient(clusterConf) 25 } 26 27 // newClusterClient new a ClusterClient 28 func newClusterClient(clusterConf *config.Cluster) *redis.ClusterClient { 29 30 adders := make([]string, 0) 31 for _, node := range clusterConf.Nodes { 32 adders = append(adders, node.To()) 33 } 34 35 options := redis.ClusterOptions{ 36 Addrs: adders, 37 DialTimeout: clusterConf.DialTimeout * time.Millisecond, 38 ReadTimeout: clusterConf.ReadTimeout * time.Millisecond, 39 WriteTimeout: clusterConf.WriteTimeout * time.Millisecond, 40 Password: clusterConf.Password, 41 PoolSize: clusterConf.PoolSize, 42 ReadOnly: clusterConf.ReadOnly, 43 PoolTimeout: 30 * time.Second, 44 IdleTimeout: 10 * time.Second, 45 IdleCheckFrequency: 1 * time.Second, 46 } 47 48 return redis.NewClusterClient(&options) 49 } 50 51 // newClient 新建连接池 52 func newClient(clusterConf []*config.Cluster) *Client { 53 client := Client{} 54 for _, clusterConfig := range clusterConf { 55 cluster := newClusterClient(clusterConfig) 56 client.Clusters = append(client.Clusters, cluster) 57 } 58 59 client.R = 1 60 client.W = 1 61 client.ReadTimeout = time.Millisecond * 200000 62 client.WriteTimeout = time.Millisecond * 200000 63 64 if client.W > len(client.Clusters) { 65 client.W = len(client.Clusters) 66 } 67 68 if client.R > len(client.Clusters) { 69 client.R = len(client.Clusters) 70 } 71 72 return &client 73 } 74 75 // Get 获取线程池 76 func Get() *Client { 77 return pool 78 } 79 80 func getClusterClient(c *Client) (*redis.ClusterClient, error) { 81 if len(c.Clusters) == 0 { 82 return nil, fmt.Errorf("Clusters is 0") 83 } 84 return c.Clusters[0], nil 85 }