89 lines
1.6 KiB
Go
89 lines
1.6 KiB
Go
package reconnect
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sync"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// RedisClient Redis客户端包装器
|
|
type RedisClient struct {
|
|
options *redis.Options
|
|
client *redis.Client
|
|
mu sync.RWMutex
|
|
}
|
|
|
|
// NewRedisClient 创建新的Redis客户端
|
|
func NewRedisClient(options *redis.Options) *RedisClient {
|
|
return &RedisClient{
|
|
options: options,
|
|
}
|
|
}
|
|
|
|
// Connect 建立Redis连接
|
|
func (r *RedisClient) Connect(ctx context.Context) error {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
|
|
if r.client != nil {
|
|
_ = r.client.Close()
|
|
}
|
|
|
|
client := redis.NewClient(r.options)
|
|
if err := client.Ping(ctx).Err(); err != nil {
|
|
return fmt.Errorf("redis ping failed: %w", err)
|
|
}
|
|
|
|
r.client = client
|
|
return nil
|
|
}
|
|
|
|
// Close 关闭Redis连接
|
|
func (r *RedisClient) Close() error {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
|
|
if r.client != nil {
|
|
err := r.client.Close()
|
|
r.client = nil
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Ping 检查Redis连接是否健康
|
|
func (r *RedisClient) Ping(ctx context.Context) error {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
|
|
if r.client == nil {
|
|
return fmt.Errorf("redis client is nil")
|
|
}
|
|
|
|
return r.client.Ping(ctx).Err()
|
|
}
|
|
|
|
// IsConnected 检查连接状态
|
|
func (r *RedisClient) IsConnected() bool {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
|
|
return r.client != nil
|
|
}
|
|
|
|
// GetClient 获取底层的Redis客户端
|
|
func (r *RedisClient) GetClient() *redis.Client {
|
|
r.mu.RLock()
|
|
defer r.mu.RUnlock()
|
|
|
|
return r.client
|
|
}
|
|
|
|
// RedisManager 创建Redis重连管理器
|
|
func RedisManager(options *redis.Options, config *Config) *Manager {
|
|
client := NewRedisClient(options)
|
|
return NewManager(client, config)
|
|
}
|