91 lines
2.1 KiB
Go
91 lines
2.1 KiB
Go
package redisConnectUtil
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"log"
|
||
"time"
|
||
|
||
"github.com/go-redis/redis/v8"
|
||
)
|
||
|
||
var (
|
||
RedisClient *redis.Client
|
||
ctx = context.Background()
|
||
)
|
||
|
||
// InitRedis 初始化Redis连接
|
||
func InitRedis(host, password string, port, db int) error {
|
||
// 如果Redis客户端已经存在且连接正常,直接返回
|
||
if RedisClient != nil {
|
||
_, err := RedisClient.Ping(ctx).Result()
|
||
if err == nil {
|
||
log.Println("Redis连接已存在且正常")
|
||
return nil
|
||
}
|
||
// 连接异常,重新初始化
|
||
log.Println("Redis连接异常,重新初始化")
|
||
}
|
||
|
||
RedisClient = redis.NewClient(&redis.Options{
|
||
Addr: fmt.Sprintf("%s:%d", host, port),
|
||
Password: password,
|
||
DB: db,
|
||
})
|
||
|
||
log.Printf("开始连接Redis.... Addr: %s:%d, password:%s, db:%d", host, port, password, db)
|
||
// 测试连接
|
||
_, err := RedisClient.Ping(ctx).Result()
|
||
if err != nil {
|
||
return fmt.Errorf("Redis连接失败: %v", err)
|
||
}
|
||
|
||
log.Println("Redis连接成功")
|
||
return nil
|
||
}
|
||
|
||
// CloseRedis 关闭Redis连接
|
||
func CloseRedis() {
|
||
if RedisClient != nil {
|
||
RedisClient.Close()
|
||
log.Println("Redis连接已关闭")
|
||
}
|
||
}
|
||
|
||
// AcquireLock 获取分布式锁
|
||
func AcquireLock(lockKey string, timeout time.Duration) (bool, error) {
|
||
// 检查Redis客户端是否已初始化
|
||
if RedisClient == nil {
|
||
// 初始化Redis连接
|
||
err := InitRedis("36.212.20.113", "j8nZ4jra2E", 7963, 13)
|
||
if err != nil {
|
||
return false, fmt.Errorf("Redis连接初始化失败: %v", err)
|
||
}
|
||
}
|
||
|
||
// 尝试获取锁,设置过期时间防止死锁
|
||
result, err := RedisClient.SetNX(ctx, lockKey, "1", timeout).Result()
|
||
if err != nil {
|
||
return false, fmt.Errorf("获取Redis锁失败: %v", err)
|
||
}
|
||
return result, nil
|
||
}
|
||
|
||
// ReleaseLock 释放分布式锁
|
||
func ReleaseLock(lockKey string) error {
|
||
// 检查Redis客户端是否已初始化
|
||
if RedisClient == nil {
|
||
// 初始化Redis连接
|
||
err := InitRedis("36.212.20.113", "j8nZ4jra2E", 7963, 13)
|
||
if err != nil {
|
||
return fmt.Errorf("Redis连接初始化失败: %v", err)
|
||
}
|
||
}
|
||
|
||
_, err := RedisClient.Del(ctx, lockKey).Result()
|
||
if err != nil {
|
||
return fmt.Errorf("释放Redis锁失败: %v", err)
|
||
}
|
||
return nil
|
||
}
|