commit
This commit is contained in:
44
go_backend/database/redis.go
Normal file
44
go_backend/database/redis.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"ai_xhs/config"
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var RDB *redis.Client
|
||||
|
||||
// InitRedis 初始化Redis连接
|
||||
func InitRedis() error {
|
||||
cfg := config.AppConfig.Redis
|
||||
|
||||
RDB = redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
PoolSize: cfg.PoolSize,
|
||||
})
|
||||
|
||||
// 测试连接
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := RDB.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("Redis连接失败: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("Redis连接成功: %s:%d (DB:%d)", cfg.Host, cfg.Port, cfg.DB)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CloseRedis 关闭Redis连接
|
||||
func CloseRedis() error {
|
||||
if RDB != nil {
|
||||
return RDB.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user