58 lines
1.6 KiB
Go
58 lines
1.6 KiB
Go
package database
|
|
|
|
import (
|
|
"cloudnest/internal/pkg/logger"
|
|
"github.com/go-redis/redis/v8"
|
|
)
|
|
|
|
// RedisClient provides Redis cache operations.
|
|
// RedisClient 提供 Redis 缓存操作。
|
|
//
|
|
// This struct wraps the go-redis client and provides methods for cache operations.
|
|
//
|
|
// 此结构体封装了 go-redis 客户端,并提供了缓存操作的方法。
|
|
type RedisClient struct {
|
|
Client *redis.Client
|
|
}
|
|
|
|
// NewRedisClient creates a new Redis client.
|
|
// NewRedisClient 创建一个新的 Redis 客户端。
|
|
//
|
|
// Parameters:
|
|
// - addr: The Redis server address (host:port).
|
|
// - password: The Redis password (empty string for no password).
|
|
// - db: The Redis database number (0-15).
|
|
//
|
|
// Returns:
|
|
// - *RedisClient: A pointer to the new RedisClient instance.
|
|
// - error: An error if the connection fails.
|
|
//
|
|
// Note:
|
|
// - A PING command is sent to verify the connection.
|
|
//
|
|
// 参数:
|
|
// - addr: Redis 服务器地址(host:port)。
|
|
// - password: Redis 密码(无密码时为空字符串)。
|
|
// - db: Redis 数据库编号(0-15)。
|
|
//
|
|
// 返回值:
|
|
// - *RedisClient: 新创建的 RedisClient 实例指针。
|
|
// - error: 如果连接失败则返回错误。
|
|
//
|
|
// 注意:
|
|
// - 会发送 PING 命令来验证连接。
|
|
func NewRedisClient(addr, password string, db int) (*RedisClient, error) {
|
|
client := redis.NewClient(&redis.Options{
|
|
Addr: addr,
|
|
Password: password,
|
|
DB: db,
|
|
})
|
|
|
|
_, err := client.Ping(client.Context()).Result()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
logger.Info("redis connected")
|
|
return &RedisClient{Client: client}, nil
|
|
} |