12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package lock
- import (
- "context"
- "eta/eta_mini_ht_api/common/component/cache"
- "fmt"
- "github.com/go-redis/redis/v8"
- )
- const (
- lockName = "lock:"
- )
- var (
- ctx = context.Background()
- rdb = cache.GetInstance()
- )
- func AcquireLock(key string, expiration int, Holder string) bool {
- script := redis.NewScript(`local key = KEYS[1]
- local clientId = ARGV[1]
- local expiration = tonumber(ARGV[2])
- if redis.call("EXISTS", key) == 0 then
- redis.call("SET", key, clientId, "EX", expiration)
- return 1
- else
- return 0
- end`)
- lockey := fmt.Sprintf("%s%s", lockName, key)
- result, err := script.Run(ctx, rdb.RedisClient(), []string{lockey}, Holder, expiration).Int()
- if err != nil {
- return false
- }
- if result == 1 {
- return true
- }
- return false
- }
- func ReleaseLock(key string, holder string) bool {
- script := redis.NewScript(`
- if redis.call("get", KEYS[1]) == ARGV[1] then
- return redis.call("del", KEYS[1])
- else
- return 0
- end
- `)
- lockey := fmt.Sprintf("%s%s", lockName, key)
- result, err := script.Run(ctx, rdb.RedisClient(), []string{lockey}, holder).Int()
- if err != nil {
- return false
- }
- if result == 1 {
- return true
- }
- return false
- }
|