Redis分布式锁防止高并发

11 篇文章 0 订阅
5 篇文章 0 订阅

场景:抢购
1.控制器层

了解一下或许有帮助:分布式开发杂谈

/**
 * 抢购
 * */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {
	@Autowired
	private RedisNxUtil redisNxUtil;
	/**
	 * 分布式锁实现抢购
	 * 2020-04-14
	 * */
	@RequestMapping(value = "/buy", method = RequestMethod.POST)
	public void buy(Integer uid, @RequestBody BuyDto buyRequest) {
	    if (uid == null) {
	        throw new AppException(FinancialCodeConst.NO_LOGIN);
	    }
	    // 获取锁的key,原则是同一个抢购使用同一个锁
	    String key = "FinancialProduct:" + buyRequest.getProductId();
	    // 获取锁,即添加一个锁
	    boolean lock = redisNxUtil.lock(key);
	    if (lock) {
	        try {
	        	// 允许执行本次购买,开始购买
	            buyProduct(buyRequest, uid);
	        } catch (Exception e) {
	            throw e;
	        } finally {
	            redisNxUtil.delete(key);
	        }
	    } else {
	        // 若没有获取到锁,则表示当前锁已被占用,等待再次获取锁
            int failCount = 1;
            // 记录是否成功获取锁,防止成功后再次进入循环
            boolean isSuccess = false;
	        // 设置失败次数计数器, 当到达5次时, 返回失败
	        while (failCount <= 5 && !isSuccess) {
	            // 等待100ms重试
	            try {
	                Thread.sleep(100L);
	            } catch (InterruptedException e) {
	                e.printStackTrace();
	            }
	            if (redisNxUtil.lock(key)) {
	                try {
	                	// 允许执行本次购买,开始购买
	                    buyProduct(buyRequest, uid);
	                } catch (Exception e) {
	                    throw e;
	                } finally {
	                    redisNxUtil.delete(key);
	                }
	                isSuccess = true;
	            } else {
	                failCount++;
	            }
	        }
	        if (!isSuccess) {
                throw new AppException("当前购买人数太多请稍后重试");
            }
	    }
	}

	/**
	* 开始购买
	*/
	private void buyProduct(BuyDto buyRequest, Integer uid) {
		...
	}
}

2.Redis的锁处理

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;
/**
 * RedisNXUtil
 */
@Component
public class RedisNxUtil {
	public static final String LOCK_PREFIX = "REDIS_NX_LOCK";
	/**
     * ms
     */
    public static final int LOCK_EXPIRE = 300;
    
    @Autowired
    private RedisTemplate redisTemplate;
	/**
     * 分布式锁(防止死锁)
     *
     * @param key key
     * @return 是否获取到
     */
    public boolean lock(String key) {
        String lock = LOCK_PREFIX + ":" + key;
        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
            long exprieAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
            Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(exprieAt).getBytes());

            if (acquire) {
                return true;
            } else {
                byte[] value = connection.get(lock.getBytes());
                if (Objects.nonNull(value) && value.length > 0) {
                    long expireTime = Long.parseLong(new String(value));
                    if (expireTime < System.currentTimeMillis()) {
                        // 如果锁已经过期
                        byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
                        // 防止死锁
                        return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
                    }
                }
            }
            return false;
        });
    }

    /**
     * 删除锁
     *
     * @param key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }
}

3.php版本
原理和java是一致的

/**
     * redis分布式锁
     * @param $lock
     * @param int $expireTime 过期时间:毫秒
     * @return bool
     */
    public function lock($lock, $expireTime = 5000)
    {
        $nowTimeMs = time() * 1000;
        $expireAt = $nowTimeMs + $expireTime;
        $acquire = $this->redis->setnx($lock, $expireAt);
        if ($acquire) {
            return true;
        } else {
            // 防止死锁
            $oldValue = $this->redis->get($lock);
            if (!$oldValue || $nowTimeMs > $oldValue) {
                // 如果锁已经过期,这里需要注意getSet的用法
                $lastValue = $this->redis->getSet($lock, $expireAt);
                return $lastValue < $nowTimeMs;
            }
            return false;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值