用redis做分布式锁,尝试多次获取锁

  • Post author:
  • Post category:其他


用redis做分布式锁,尝试多次获取锁

核心业务代码

 		boolean lock = false;
        int i = 0;
        //重复三次获取锁
        for (i = 0; i < 3; i++) {
        //获取锁
            lock = RedisClient.setIfAbsent(CouponCacheKey.REMAIN_LOCK_KEY , "lock", 10, TimeUnit.SECONDS);
            if (lock) {
                break;
            } else {
                try {
               		//一秒后重试获取锁
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if (i == 3) {
            throw new HelpUpdateException("网络繁忙,请稍候重试", HelpStatus.NET_ERROR);
        }
		******
		被锁住的业务代码
		******
		//删除锁
        RedisClient.del(CouponCacheKey.PERSON_COUPON_LOCK_KEY);



版权声明:本文为zyw_hello原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。