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.
go-library/utils/golock/redis.go

68 lines
1.5 KiB

2 years ago
package golock
import (
2 years ago
"context"
"errors"
2 years ago
"github.com/dtapps/go-library/utils/dorm"
2 years ago
"time"
)
type LockRedis struct {
2 years ago
client *dorm.RedisClient // 驱动
2 years ago
}
2 years ago
func NewLockRedis(client *dorm.RedisClient) *LockRedis {
return &LockRedis{client: client}
2 years ago
}
// Lock 上锁
2 years ago
// key 锁名
// val 锁内容
// ttl 锁过期时间
func (r *LockRedis) Lock(ctx context.Context, key string, val string, ttl time.Duration) (resp string, err error) {
2 years ago
if ttl <= 0 {
2 years ago
return resp, errors.New("长期请使用 LockForever 方法")
2 years ago
}
2 years ago
// 获取
get, err := r.client.Get(ctx, key).Result()
2 years ago
if err != nil {
2 years ago
return resp, errors.New("获取异常")
2 years ago
}
if get != "" {
2 years ago
return resp, errors.New("上锁失败,已存在")
2 years ago
}
2 years ago
// 设置
err = r.client.Set(ctx, key, val, ttl).Err()
2 years ago
if err != nil {
2 years ago
return resp, errors.New("上锁失败")
2 years ago
}
return val, nil
2 years ago
}
2 years ago
// Unlock 解锁
// key 锁名
func (r *LockRedis) Unlock(ctx context.Context, key string) error {
_, err := r.client.Del(ctx, key).Result()
2 years ago
return err
2 years ago
}
// LockForever 永远上锁
2 years ago
// key 锁名
// val 锁内容
func (r *LockRedis) LockForever(ctx context.Context, key string, val string) (resp string, err error) {
2 years ago
// 获取
get, err := r.client.Get(ctx, key).Result()
2 years ago
if err != nil {
2 years ago
return resp, errors.New("获取异常")
2 years ago
}
if get != "" {
2 years ago
return resp, errors.New("上锁失败,已存在")
2 years ago
}
2 years ago
// 设置
err = r.client.Set(ctx, key, val, 0).Err()
2 years ago
if err != nil {
2 years ago
return resp, errors.New("上锁失败")
2 years ago
}
2 years ago
return val, nil
2 years ago
}