高并发下的分布式锁

模板网 2021-04-14
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

相关文章

  1. redis 运维常用命令

    time #查看时间戳与微妙数 dbsize #查看当前数据库中key数量 bgrewriteaof #后台进程重写aof bgsave #后台保存rdb快照 save #保存rd

  2. aof恢复与rdb服务器迁移

    一、不小心flushall或flushdb了怎么办??? 只有aof还不够。 因为如果发生重写,aof文件里就什么都没有了。 所以要及时shutdown nosave,防止aof重写!!! 然后将a

  3. 常见排序列表

    常见排序列表 中文名称 英文名称 平均时间复杂度 最坏时间复杂度 最好时间复杂度 空间复杂度 稳定性 选择排序 Selection n^2 n^2 n^2 1 不稳 冒泡排序 Bub

  4. 使用create-react-app快速搭建react环境

    使用create-react-app快速搭建react环境 npm install create-react-app -g cd test_dir create-react-app demo_rea

  5. gitlab备份与恢复

    一、gitlab备份 [root@localhost ~]# gitlab-rake gitlab:backup:create Dumping database ... Dumping Postgr

随机推荐

  1. redis 运维常用命令

    time #查看时间戳与微妙数 dbsize #查看当前数据库中key数量 bgrewriteaof #后台进程重写aof bgsave #后台保存rdb快照 save #保存rd

  2. aof恢复与rdb服务器迁移

    一、不小心flushall或flushdb了怎么办??? 只有aof还不够。 因为如果发生重写,aof文件里就什么都没有了。 所以要及时shutdown nosave,防止aof重写!!! 然后将a

  3. 常见排序列表

    常见排序列表 中文名称 英文名称 平均时间复杂度 最坏时间复杂度 最好时间复杂度 空间复杂度 稳定性 选择排序 Selection n^2 n^2 n^2 1 不稳 冒泡排序 Bub

  4. 使用create-react-app快速搭建react环境

    使用create-react-app快速搭建react环境 npm install create-react-app -g cd test_dir create-react-app demo_rea

  5. gitlab备份与恢复

    一、gitlab备份 [root@localhost ~]# gitlab-rake gitlab:backup:create Dumping database ... Dumping Postgr