You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.4 KiB
67 lines
1.4 KiB
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
|
|
}
|