61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
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))
|
||
}
|