demo1 public ErrorCode initDemo1(@RequestParam("orderNo") String orderNo) throws IOException { String lockKey = KEY + orderNo; Boolean hasKey = null; try { //锁判断 hasKey = redistemplate.hasKey(lockKey); int index = 0; while (hasKey && index < 3) { log.info(">>>>>>>>>>>>>刷新,wait>>>>>>>>>>>>>"); index++; Thread.sleep(1500L * index); hasKey = redistemplate.hasKey(lockKey); } if (index > 0) { log.info(">>>>>>>>>>>>>wait index:{} hasKey: {}", index, hasKey); } //加锁 redistemplate.opsForValue().set(lockKey, "1", 5, TimeUnit.SECONDS); //业务操作-刷新es todo 业务逻辑 //去锁 redistemplate.delete(lockKey); return ErrorCode.SUCCESS; } catch (Exception e) { //去锁 redistemplate.delete(lockKey); return ErrorCode.SYS_ERROR; } } demo2 public ErrorCode initDemo2(@RequestParam("orderNo") String orderNo) throws IOException { String lockKey = KEY + orderNo; Boolean hasKey = null; try { hasKey = lock(lockKey, orderNo, 5); if(hasKey != null && hasKey) { //业务操作-刷新es todo 业务逻辑 }else { return ErrorCode.LOCK_Failed; } return ErrorCode.SUCCESS; } catch (Exception e) { return ErrorCode.SYS_ERROR; } finally{ if(hasKey != null && hasKey) { redistemplate.delete(lockKey); } } } public boolean lock(String key, String value, long releaseTime) { // 尝试获取锁 spring-data-redis 2.1版本以上 //implementation group: 'org.springframework.data', name: 'spring-data-redis', version: '2.1.0.RELEASE' // Boolean boo = redistemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS); //.setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS); // 判断结果 // return boo != null && boo; redistemplate.setEnableTransactionSupport(true); redistemplate.multi(); redistemplate.opsForValue().setIfAbsent(key,value); redistemplate.expire(key,releaseTime, TimeUnit.SECONDS); List result = redistemplate.exec(); // 这里result会返回事务内每一个操作的结果,如果setIfAbsent操作失败后,result[0]会为false。 if(result != null && true == (Boolean)result.get(0)){ return true; }else { return false; } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。