标签:server on() gre cep exce boolean pos ring and
一: 使用redis:
@PostMapping("/v1/getLock2") public BaseResponse getLock2(@RequestBody GxyTeacherInfoDto dto) throws Exception{ String key = "product_001"; String lockvalue = UUID.randomUUID().toString(); Boolean bool = stringRedisTemplate.opsForValue().setIfAbsent(key,lockvalue,10,TimeUnit.SECONDS); if(!bool) { System.out.println("err"); return BaseResponse.error(); } try { int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock")); if (stock > 0) { int realStock = stock - 1; stringRedisTemplate.opsForValue().set("stock",realStock+""); System.out.println("售卖成功,剩余" + realStock); return BaseResponse.ok(); } else { System.out.println("err2"); return BaseResponse.error(); } } finally { if(lockvalue.equals(stringRedisTemplate.opsForValue().get(key))) { stringRedisTemplate.delete(key); } } }
二: 使用Redisson:
@Bean public Redisson redisson(){ Config config = new Config(); config.useSingleServer().setAddress("redis://IP:port"); return (Redisson)Redisson.create(config); }
@PostMapping("/v1/getLock3") public BaseResponse getLock3(@RequestBody GxyTeacherInfoDto dto) throws Exception{ String lockKey = "product_001"; RLock redissonLock = redisson.getLock(lockKey); try { int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock")); if (stock > 0) { int realStock = stock - 1; stringRedisTemplate.opsForValue().set("stock",realStock+""); System.out.println("售卖成功,剩余" + realStock); return BaseResponse.ok(); } else { System.out.println("err2"); return BaseResponse.error(); } } finally { redissonLock.unlock(); } }
标签:server on() gre cep exce boolean pos ring and
原文地址:https://www.cnblogs.com/z360519549/p/12499050.html