| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- package database
- import (
- "context"
- "fmt"
- "time"
- "github.com/go-redis/redis/v8"
-
- "newaterobot-process/config"
- )
- var RedisClient *redis.Client
- // InitRedis 初始化Redis连接
- func InitRedis() error {
- redisConfig := config.GlobalConfig.Redis
-
- // 创建Redis客户端
- RedisClient = redis.NewClient(&redis.Options{
- Addr: fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port),
- Password: redisConfig.Password,
- DB: redisConfig.DB,
- PoolSize: redisConfig.PoolSize,
- })
- // 测试连接
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
-
- _, err := RedisClient.Ping(ctx).Result()
- if err != nil {
- return fmt.Errorf("failed to connect to Redis: %v", err)
- }
- return nil
- }
- // CloseRedis 关闭Redis连接
- func CloseRedis() error {
- if RedisClient != nil {
- return RedisClient.Close()
- }
- return nil
- }
|