62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
package redisConnectUtil
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/go-redis/redis/v8"
|
|
)
|
|
|
|
// InitRedis 初始化Redis连接
|
|
func InitRedis(addr, password string, db int) *redis.Client {
|
|
|
|
log.Print("初始化Redis连接.....")
|
|
|
|
client := redis.NewClient(&redis.Options{
|
|
Addr: addr,
|
|
Password: password,
|
|
DB: db,
|
|
PoolSize: 10,
|
|
OnConnect: func(ctx context.Context, cn *redis.Conn) error {
|
|
// 连接建立后立即选择数据库
|
|
if db > 0 {
|
|
return cn.Select(ctx, db).Err()
|
|
}
|
|
return nil
|
|
},
|
|
})
|
|
|
|
// 测试连接
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
if _, err := client.Ping(ctx).Result(); err != nil {
|
|
log.Fatalf("Redis连接失败: %v", err)
|
|
}
|
|
|
|
log.Printf("Redis连接成功: addr=%s, db=%d", addr, db)
|
|
|
|
return client
|
|
}
|
|
|
|
// SafeCloseRedis 安全关闭Redis连接
|
|
func SafeCloseRedis(client *redis.Client) {
|
|
|
|
log.Print("安全关闭Redis连接.....")
|
|
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
log.Printf("Redis关闭时发生panic: %v", r)
|
|
}
|
|
}()
|
|
|
|
if client != nil {
|
|
if err := client.Close(); err != nil {
|
|
log.Printf("Redis关闭错误: %v", err)
|
|
} else {
|
|
log.Println("Redis连接已安全关闭")
|
|
}
|
|
}
|
|
}
|