42 lines
966 B
Go
42 lines
966 B
Go
package lxLock
|
|
|
|
import (
|
|
"context"
|
|
"gitea.listensoft.net/tool/lxutils/lxDb"
|
|
"github.com/go-redis/redis/v8"
|
|
"time"
|
|
)
|
|
|
|
// RedisPool Redis连接池
|
|
var RedisClient *redis.Client
|
|
var redisCtx = context.Background()
|
|
|
|
func InitRedis(conf lxDb.RedisConfig) {
|
|
if conf.URL == "" {
|
|
RedisClient = nil
|
|
return
|
|
}
|
|
RedisClient = redis.NewClient(&redis.Options{
|
|
Addr: conf.URL, // Redis 服务器地址
|
|
Password: conf.Password, // Redis 密码
|
|
DB: 0, // 默认数据库
|
|
})
|
|
}
|
|
|
|
// GetRedisLock 尝试获取锁
|
|
func GetRedisLock(lockKey string, expiration time.Duration) (bool, error) {
|
|
// 使用 SETNX 命令尝试获取锁
|
|
result, err := RedisClient.SetNX(redisCtx, lockKey, "locked", expiration).Result()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// DelRedisLock 释放锁
|
|
func DelRedisLock(lockKey string) error {
|
|
// 使用 DEL 命令释放锁
|
|
_, err := RedisClient.Del(redisCtx, lockKey).Result()
|
|
return err
|
|
}
|