init
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"skeleton/config"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// RedisClient Redis客户端封装
|
||||
type RedisClient struct {
|
||||
client *redis.Client
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
var redisClient *RedisClient
|
||||
|
||||
// InitRedis 初始化Redis客户端
|
||||
func InitRedis(cfg *config.Config, logger *zap.Logger) error {
|
||||
// 创建Redis客户端配置
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%d", cfg.Redis.Host, cfg.Redis.Port),
|
||||
Password: cfg.Redis.Password,
|
||||
DB: cfg.Redis.Database,
|
||||
PoolSize: cfg.Redis.PoolSize,
|
||||
MinIdleConns: cfg.Redis.MinIdleConns,
|
||||
MaxRetries: cfg.Redis.MaxRetries,
|
||||
})
|
||||
|
||||
// 测试连接
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := rdb.Ping(ctx).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Redis连接失败: %w", err)
|
||||
}
|
||||
|
||||
// 创建全局Redis客户端实例
|
||||
redisClient = &RedisClient{
|
||||
client: rdb,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
logger.Info("Redis客户端初始化成功",
|
||||
zap.String("host", cfg.Redis.Host),
|
||||
zap.Int("port", cfg.Redis.Port),
|
||||
zap.Int("database", cfg.Redis.Database),
|
||||
zap.Int("pool_size", cfg.Redis.PoolSize))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRedisClient 获取Redis客户端实例
|
||||
func GetRedisClient() *RedisClient {
|
||||
return redisClient
|
||||
}
|
||||
|
||||
// Close 关闭Redis连接
|
||||
func (r *RedisClient) Close() error {
|
||||
if r != nil && r.client != nil {
|
||||
return r.client.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user