2025-08-05 10:51:35 +08:00
|
|
|
package clients
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"log/slog"
|
|
|
|
|
"os"
|
2025-08-19 11:09:58 +08:00
|
|
|
|
2025-09-10 18:26:59 +08:00
|
|
|
"github.com/redis/go-redis/v9"
|
2025-08-05 10:51:35 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var Redis *redis.Client
|
|
|
|
|
|
|
|
|
|
func InitRedis() {
|
|
|
|
|
host := os.Getenv("REDIS_HOST")
|
|
|
|
|
if host == "" {
|
|
|
|
|
slog.Debug("REDIS_HOST 环境变量未设置,使用默认值 localhost")
|
|
|
|
|
host = "localhost"
|
|
|
|
|
}
|
|
|
|
|
port := os.Getenv("REDIS_PORT")
|
|
|
|
|
if port == "" {
|
|
|
|
|
slog.Debug("REDIS_PORT 环境变量未设置,使用默认值 6379")
|
|
|
|
|
port = "6379"
|
|
|
|
|
}
|
|
|
|
|
password := os.Getenv("REDIS_PASSWORD")
|
|
|
|
|
if password == "" {
|
|
|
|
|
slog.Debug("REDIS_PASSWORD 环境变量未设置,使用默认值空字符串")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Redis = redis.NewClient(&redis.Options{
|
|
|
|
|
Addr: host + ":" + port,
|
|
|
|
|
Password: password,
|
|
|
|
|
})
|
|
|
|
|
}
|
2025-08-19 11:09:58 +08:00
|
|
|
|
|
|
|
|
func CloseRedis() {
|
|
|
|
|
if Redis != nil {
|
|
|
|
|
err := Redis.Close()
|
|
|
|
|
if err != nil {
|
|
|
|
|
slog.Error("关闭 Redis 连接失败", "error", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|