使用Redis实现分布式锁实例一
作者:互联网
以下是使用Redis在高并发下实现的一把分布式锁示例,直接上代码:
@RequestMapping("/deduct_stock") public String getbykey(String key) { String lockKey = "product" + key; String uuid = UUID.randomUUID().toString(); //最简单的分布式锁 Boolean locked = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, uuid,30,TimeUnit.SECONDS); if(!locked){ return "error_code"; } try{ synchronized (this) { String result = stringRedisTemplate.opsForValue().get(key); if (StringUtils.hasLength(result)) { int number = Integer.parseInt(result); if (number > 0) { number--; stringRedisTemplate.opsForValue().set("stock", number + ""); System.out.println("库存为:" + number); }else{ System.out.println("库存不足"); } } return result; } }finally { if(uuid.equals(stringRedisTemplate.opsForValue().get(lockKey))) { stringRedisTemplate.delete(lockKey); } } }
标签:String,opsForValue,Redis,number,lockKey,实例,result,stringRedisTemplate,分布式 来源: https://www.cnblogs.com/skyfreedom/p/16394805.html