41 lines
740 B
Go
41 lines
740 B
Go
package redis
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/company/ai-ops/internal/config"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// Client 是全局 Redis 客户端
|
|
var Client *redis.Client
|
|
|
|
// Init 初始化 Redis 连接
|
|
func Init(cfg config.RedisConfig) error {
|
|
Client = redis.NewClient(&redis.Options{
|
|
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
|
|
Password: cfg.Password,
|
|
DB: cfg.DB,
|
|
PoolSize: 10,
|
|
})
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
if err := Client.Ping(ctx).Err(); err != nil {
|
|
return fmt.Errorf("ping redis: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Close 关闭 Redis 连接
|
|
func Close() error {
|
|
if Client != nil {
|
|
return Client.Close()
|
|
}
|
|
return nil
|
|
}
|