| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package redisx
- import (
- "context"
- "fmt"
- "sync"
- "time"
- "github.com/redis/go-redis/v9"
- )
- // 统一初始化与连接管理(支持单机、哨兵、集群)
- var (
- client redis.UniversalClient
- once sync.Once
- )
- type Config struct {
- Mode string
- Addrs []string
- Username string
- Password string
- DB int
- MasterName string
- PoolSize int
- MinIdleConns int
- DialTimeout time.Duration
- ReadTimeout time.Duration
- WriteTimeout time.Duration
- }
- func Init(cfg *Config) {
- once.Do(func() {
- client = redis.NewUniversalClient(&redis.UniversalOptions{
- Addrs: cfg.Addrs,
- Username: cfg.Username,
- Password: cfg.Password,
- DB: cfg.DB,
- MasterName: cfg.MasterName,
- PoolSize: cfg.PoolSize,
- MinIdleConns: cfg.MinIdleConns,
- DialTimeout: cfg.DialTimeout,
- ReadTimeout: cfg.ReadTimeout,
- WriteTimeout: cfg.WriteTimeout,
- })
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
- if ping := client.Do(ctx, "PING"); ping.Err() != nil {
- fmt.Println(cfg.Addrs)
- errStr := fmt.Sprintf("Redis 无法访问: %s", ping.Err().Error())
- panic(errStr)
- }
- })
- }
- // getClient 获取 Redis 客户端
- func getClient() redis.UniversalClient {
- if client == nil {
- panic("redisx not initialized, call redisx.Init() first")
- }
- return client
- }
- // Close 关闭 Redis 连接
- func Close() error {
- if client != nil {
- return client.Close()
- }
- return nil
- }
|