39 lines
772 B
Go
39 lines
772 B
Go
package redis
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"goalfymax-admin/internal/config"
|
|
"log"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// Client 是一个 Redis 客户端的封装
|
|
type Client struct {
|
|
Rdb *redis.Client
|
|
}
|
|
|
|
// NewClient 创建一个新的 Redis 客户端实例
|
|
func NewClient(cfg config.RedisConfig) (*Client, error) {
|
|
rdb := redis.NewClient(&redis.Options{
|
|
Addr: cfg.Addr,
|
|
Password: cfg.Password,
|
|
DB: cfg.DB,
|
|
})
|
|
|
|
ctx := context.Background()
|
|
if _, err := rdb.Ping(ctx).Result(); err != nil {
|
|
rdb.Close()
|
|
return nil, fmt.Errorf("failed to connect to Redis: %w", err)
|
|
}
|
|
|
|
log.Println("Successfully connected to Redis")
|
|
return &Client{Rdb: rdb}, nil
|
|
}
|
|
|
|
// Close 关闭 Redis 客户端连接
|
|
func (c *Client) Close() error {
|
|
return c.Rdb.Close()
|
|
}
|