1、
2.加锁、释放锁
/**
* 获取sn号,申请人传入号段,与需要申请的sn个数,返回生成的sn号,并将本次申请记录计入发号申请记录,需要传设备分段标记
* @return
*/
@SysLog("申请sn发号")
@RequestMapping(value = "getSns", method = RequestMethod.POST)
public ResultWarp getSns(HttpServletResponse response, @RequestBody TSnIssuerecordEntity issueRecode) {
//非空验证
if (StringUtil.strIsNullOrEmpty(issueRecode.getSnum())) return new ResultWarp(ResultWarp.FAILED, "号段为空");
if (StringUtil.strIsNullOrEmpty(issueRecode.getRemark())) return new ResultWarp(ResultWarp.FAILED, "类别为空");
if (StringUtil.strIsNullOrEmpty(issueRecode.getNum())) return new ResultWarp(ResultWarp.FAILED, "申请数量为空");
String key = issueRecode.getSnum();
String value = key + System.currentTimeMillis();
try {
//加锁
while(true) {
boolean setnx = redisUtils.setnx(key, value, 600);
if (setnx) break;
}
//判断申请sn号会不会超过最大值
String result = fHservice.compareSn(issueRecode);
if (!"ok".equals(result)) {
return new ResultWarp(ResultWarp.FAILED, result);
}
//将生成的sn号回显
String fhid = IDUtil.get32UUID();
issueRecode.setFhid(fhid);//生成发号批次
List<String> sns = fHservice.getSns(issueRecode);
ResultWarp rw = new ResultWarp(ResultWarp.SUCCESS, "ok");
rw.addData("sns", sns);
rw.addData("fhid", fhid);
return rw;
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放锁
String resultValue = (String) redisUtils.get(key);
if (value.equals(resultValue)) redisUtils.delete(key);//如果不相等,说明是别人加的锁
}
return new ResultWarp(ResultWarp.FAILED, "服务异常,请稍后再试");
}