Files
2025-12-16 10:13:24 +08:00

54 lines
1.2 KiB
Go

package redisclient
import (
"context"
"fmt"
"os"
"github.com/redis/go-redis/v9"
)
var RDB *redis.Client
func Init() {
redisHost := os.Getenv("REDIS_HOST")
if redisHost == "" {
redisHost = "localhost"
}
redisPort := os.Getenv("REDIS_PORT")
if redisPort == "" {
redisPort = "6379"
}
redisPassword := os.Getenv("REDIS_PASSWORD")
if redisPassword == "" {
redisPassword = ""
}
// Configure Redis client with security settings
opts := &redis.Options{
Addr: fmt.Sprintf("%s:%s", redisHost, redisPort),
Password: redisPassword,
DB: 0,
DisableIndentity: true, // Disable client-side caching to prevent protocol confusion
IdentitySuffix: "", // Disable identity suffix
}
RDB = redis.NewClient(opts)
// Test connection with authentication
ctx := context.Background()
_, err := RDB.Ping(ctx).Result()
if err != nil {
panic(fmt.Sprintf("Could not connect to Redis: %v", err))
}
// Log connection security status
if redisPassword != "" {
fmt.Println("✓ Redis connection secured with password authentication")
} else {
fmt.Println("⚠ WARNING: Redis connection without password - security risk!")
}
}