2024-12-18 23:38:28 +08:00

61 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package myRedis
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
"log"
"sync"
)
type SimpleRedis struct {
Host string
Password string
hosts map[int]*Hosts
}
type Hosts struct {
clientOnce sync.Once
client *redis.Client
}
func NewSimpleRedis(host string, password string) *SimpleRedis {
return &SimpleRedis{Host: host, Password: password, hosts: map[int]*Hosts{}}
}
func (t *SimpleRedis) connectRedis(index int) *redis.Client {
if t.hosts[index] == nil {
t.hosts[index] = &Hosts{
clientOnce: sync.Once{},
client: nil,
}
}
t.hosts[index].clientOnce.Do(func() {
redisClient := redis.NewClient(&redis.Options{
Addr: t.Host,
Password: t.Password, // no password set
DB: index, // use default DB
//连接池容量以闲置链接数量
PoolSize: 15,
MinIdleConns: 10,
})
pong, err := redisClient.Ping(context.Background()).Result()
if err != nil {
panic(fmt.Errorf("connect error:%s", err))
}
log.Println(fmt.Sprintf("redis newClient success, index%d, pong: %s", index, pong))
t.hosts[index].client = redisClient
})
return t.hosts[index].client
}
func (t *SimpleRedis) ConnectDefaultRedis() *Client {
return t.GetRedisClient(0)
}
func (t *SimpleRedis) GetRedisClient(index int) *Client {
return NewClient(t.connectRedis(index))
}