redis lock - yaokun123/php-wiki GitHub Wiki

高并发下的分布式锁

public String deductStrck() throws InterruptedException{
    String lockKey = "product_001";    //用作一把分布式锁
    String clientId = UUID.randomUUID().toString();    //记录锁的id,防止别的线程可以解开这把锁

    try{
        //开始锁住
        //设置超时时间目的是为了防止程序突然中断而造成的死锁现象
        //锁的续命操作:时间设置为10,可以再开一个线程每3分钟检查一下看看这把锁是否存在,如果存在将过期时间再延长
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,clientId,10,TimeUnit.SECONDS)

        if(!result){
            return error;
        }

        //业务逻辑
        int stock Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
        if(stock>0){
            int realStock = stock-1;
            stringRedisTemplate.opsForValue().set("stock",realStock);
            System.out.println("扣减成功,剩余库存"+realStock);
        }else{
            System.out.println("扣减失败,库存不足");
        }
    }finally{//最终要解开这把锁
        if(clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))){//防止别的线程可以解开这把锁
            stringRedisTemplate.opsForValue().deleted(lockKey);
        }
    }
}

redisson提供完善的分布式锁:https://redisson.org