引用 https://www.jb51.net/article/251428.htm
Lock lock = new ReentrantLock();@AutowiredStringRedisTemplate redisTemplate;public static final String g01="good:01";public static final String REDIS_LOCK="good_lock";@ApiOperation("获取测试数据")@GetResource(name = "获取测试数据", path = "/getTestInfo", requiredPermission = false,requiredLogin = false)public ResponseData getTestInfo(@RequestParam ("num") int num){String value = UUID.randomUUID().toString().replace("-", "");UUID.randomUUID().toString().replace("-","");try {Boolean flag = redisTemplate.opsForValue().setIfAbsent(REDIS_LOCK, value,10, TimeUnit.SECONDS);if (!flag) return ResponseData.error("抢锁失败");log.info("抢锁成功");String result = redisTemplate.opsForValue().get(g01);int total = result==null ? 0:Integer.parseInt(result);if (total>0){total--;redisTemplate.opsForValue().set(g01,String.valueOf(total));return ResponseData.success(total);}return ResponseData.error("没有库存");}catch (Exception e){return ResponseData.error("报错");}finally { // redisTemplate.delete(REDIS_LOCK); // if (redisTemplate.opsForValue().get(REDIS_LOCK).equals(value)){ // redisTemplate.delete(REDIS_LOCK); // }Jedis jedis = null;try {jedis = new Jedis("119.45.11.7", 6379);jedis.auth("LIKZ10101006");String script = "if redis.call('get',KEYS[1]) == ARGV[1] " +"then " +"return redis.call('del',KEYS[1]) " +"else " +" return 0 " +"end";Object eval = jedis.eval(script, Collections.singletonList(REDIS_LOCK),Collections.singletonList(value));if("1".equals(eval.toString())){log.info("-----del redis lock ok....");}else {log.info("-----del redis lock error....");}}catch (Exception e){}finally {if (null!=jedis){jedis.close();}}}}
正常加锁
String value = UUID.randomUUID().toString().replace("-","");try{// 为key加一个过期时间Boolean flag = template.opsForValue().setIfAbsent(REDIS_LOCK, value,10L,TimeUnit.SECONDS);// 加锁失败if(!flag){return "抢锁失败!";}System.out.println( value+ " 抢锁成功");
谁加了锁,谁才能删锁
finally {// 谁加的锁,谁才能删除!!!!if(template.opsForValue().get(REDIS_LOCK).equals(value)){template.delete(REDIS_LOCK);}}
使用lua脚本,保证原子性
finally {// 谁加的锁,谁才能删除,使用Lua脚本,进行锁的删除 Jedis jedis = null;try{jedis = RedisUtils.getJedis();String script = "if redis.call('get',KEYS[1]) == ARGV[1] " +"then " +"return redis.call('del',KEYS[1]) " +"else " +" return 0 " +"end";Object eval = jedis.eval(script, Collections.singletonList(REDIS_LOCK), Collections.singletonList(value));if("1".equals(eval.toString())){System.out.println("-----del redis lock ok....");}else{System.out.println("-----del redis lock error ....");}}catch (Exception e){}finally {if(null != jedis){jedis.close();}}}
目前存在锁,并属于当前线程
finally {if(lock.isLocked() && lock.isHeldByCurrentThread()){lock.unlock();}}