Go Redis可重入锁

59 阅读1分钟

加锁

func luaLock(key []string, args ...interface{}) {
   client := GetRedisClient()

   var luaScript = redis.NewScript(`
local key = KEYS[1];
local threadId = ARGV[1];
local releaseTime = ARGV[2];

if(redis.call('exists', key) == 0) then
   redis.call('hset', key, threadId, '1');
   redis.call('expire', key, releaseTime);
   return 1; 
end;

if(redis.call('hexists', key, threadId) == 1) then
   redis.call('hincrby', key, threadId, 1);
   redis.call('expire', key, releaseTime);
   return 1;
end;

return 0;
`)

   n, err := luaScript.Run(client, key, args...).Result()
   if err != nil {
      panic(err)
   }

   fmt.Println(n)
}

解锁

func luaUnLock(key []string, args ...interface{}) {
   client := GetRedisClient()

   var luaScript = redis.NewScript(`
local key = KEYS[1];
local threadId = ARGV[1];

if (redis.call('hexists', key, threadId) == 0) then
   return 0;
end;

redis.call('del', key);
return 1;
`)

   n, err := luaScript.Run(client, key, args...).Result()
   if err != nil {
      panic(err)
   }

   fmt.Println(n)
}