parent
75a6f160b9
commit
8e27344f05
@ -1,3 +1,3 @@
|
||||
package dorm
|
||||
|
||||
const Version = "1.0.19"
|
||||
const Version = "1.0.20"
|
||||
|
@ -0,0 +1,66 @@
|
||||
package dorm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RedisClientLock https://github.com/go-redis/redis
|
||||
type RedisClientLock struct{}
|
||||
|
||||
// NewLock 实例化锁
|
||||
func (r *RedisClient) NewLock() *RedisClientLock {
|
||||
return &RedisClientLock{}
|
||||
}
|
||||
|
||||
// Lock 上锁
|
||||
// key 锁名
|
||||
// val 锁内容
|
||||
// ttl 锁过期时间
|
||||
func (r *RedisClient) Lock(ctx context.Context, key string, val string, ttl time.Duration) (resp string, err error) {
|
||||
if ttl <= 0 {
|
||||
return resp, errors.New("长期请使用 LockForever 方法")
|
||||
}
|
||||
// 获取
|
||||
get, err := r.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
return resp, errors.New("获取异常")
|
||||
}
|
||||
if get != "" {
|
||||
return resp, errors.New("上锁失败,已存在")
|
||||
}
|
||||
// 设置
|
||||
err = r.Set(ctx, key, val, ttl).Err()
|
||||
if err != nil {
|
||||
return resp, errors.New("上锁失败")
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
|
||||
// Unlock 解锁
|
||||
// key 锁名
|
||||
func (r *RedisClient) Unlock(ctx context.Context, key string) error {
|
||||
_, err := r.Del(ctx, key).Result()
|
||||
return err
|
||||
}
|
||||
|
||||
// LockForever 永远上锁
|
||||
// key 锁名
|
||||
// val 锁内容
|
||||
func (r *RedisClient) LockForever(ctx context.Context, key string, val string) (resp string, err error) {
|
||||
// 获取
|
||||
get, err := r.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
return resp, errors.New("获取异常")
|
||||
}
|
||||
if get != "" {
|
||||
return resp, errors.New("上锁失败,已存在")
|
||||
}
|
||||
// 设置
|
||||
err = r.Set(ctx, key, val, 0).Err()
|
||||
if err != nil {
|
||||
return resp, errors.New("上锁失败")
|
||||
}
|
||||
return val, nil
|
||||
}
|
Loading…
Reference in new issue