1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
pool.go 2.05 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-06-01 20:27 . tag 移到目录下
package pool
import (
"fmt"
"gitee.com/h79/goutils/dao/config"
"time"
"github.com/go-redis/redis/v8"
)
// Pool redis机群单例
var pool *Client
// Client 线程池类型
type Client struct {
Clusters []*redis.ClusterClient //集群
W int //写成功数
R int //读成功数
WriteTimeout time.Duration //总写时延
ReadTimeout time.Duration //总读时延
}
func NewPool(clusterConf []*config.Cluster) {
pool = newClient(clusterConf)
}
// newClusterClient new a ClusterClient
func newClusterClient(clusterConf *config.Cluster) *redis.ClusterClient {
adders := make([]string, 0)
for _, node := range clusterConf.Nodes {
adders = append(adders, node.To())
}
options := redis.ClusterOptions{
Addrs: adders,
DialTimeout: clusterConf.DialTimeout * time.Millisecond,
ReadTimeout: clusterConf.ReadTimeout * time.Millisecond,
WriteTimeout: clusterConf.WriteTimeout * time.Millisecond,
Password: clusterConf.Password,
PoolSize: clusterConf.PoolSize,
ReadOnly: clusterConf.ReadOnly,
PoolTimeout: 30 * time.Second,
IdleTimeout: 10 * time.Second,
IdleCheckFrequency: 1 * time.Second,
}
return redis.NewClusterClient(&options)
}
// newClient 新建连接池
func newClient(clusterConf []*config.Cluster) *Client {
client := Client{}
for _, clusterConfig := range clusterConf {
cluster := newClusterClient(clusterConfig)
client.Clusters = append(client.Clusters, cluster)
}
client.R = 1
client.W = 1
client.ReadTimeout = time.Millisecond * 200000
client.WriteTimeout = time.Millisecond * 200000
if client.W > len(client.Clusters) {
client.W = len(client.Clusters)
}
if client.R > len(client.Clusters) {
client.R = len(client.Clusters)
}
return &client
}
// Get 获取线程池
func Get() *Client {
return pool
}
func getClusterClient(c *Client) (*redis.ClusterClient, error) {
if len(c.Clusters) == 0 {
return nil, fmt.Errorf("Clusters is 0")
}
return c.Clusters[0], nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.68

搜索帮助