java抽奖接口

public TransResponse execute(TransRequest tRequest, HttpSession httpSession) {
TransResponse resp = new TransResponse(tRequest.getAction());
RegisterUser user = tRequest.getRegisterUser();
String FLAG_KEY = user.getId().toString();

if (CacheUtils.get(FLAG_KEY) != null && CacheUtils.get(FLAG_KEY + SUFFIX_KEY) != null) {
resp.setRetcode("202");
resp.setRetmesg("24小时之内只能抽奖两次,今天的抽奖次数已经用完");
return resp;
}

if(CacheUtils.get(FLAG_KEY) != null && CacheUtils.get(FLAG_KEY + SUFFIX_SHARE) == null) {
resp.setRetcode("203");
resp.setRetmesg("分享后可进行第二次抽奖");
return resp;
}

synchronized (new Object()) {
List<LotteryModel> models = lotteryModelManager.getAll();
Object[][] arr;
arr = new Object[models.size()][];
for (int i = 0; i < models.size(); i++) {
arr[i] = new Object[3];
arr[i][0] = models.get(i).getId();
arr[i][1] = models.get(i).getName();
arr[i][2] = models.get(i).getCount();
}
int prizedTotle = 0;
for (Object[] objects : arr) {
prizedTotle += (int) objects[2];
}
int prizedIndex = 0;
for (int i = 0; i < arr.length; i++) {
int randomNum = new Random().nextInt(prizedTotle) + 1;
if (randomNum <= (int) arr[i][2]) {
prizedIndex = i;
break;
} else {
prizedTotle = prizedTotle - (int) arr[i][2]; // 未抽中,拿走此奖项继续抽
}
}
logger.info("中奖:" + prizedIndex + " " + Arrays.asList(arr[prizedIndex]));
if (CacheUtils.get(FLAG_KEY) == null) {
CacheUtils.put(FLAG_KEY, FLAG_KEY);
} else {
CacheUtils.put(FLAG_KEY + SUFFIX_KEY, FLAG_KEY);
}

if(THANKS != prizedIndex) {
LotteryRecord record = new LotteryRecord();
record.setUserId(FLAG_KEY);
record.setMobile(user.getMobile());
record.setInfo(Arrays.asList(arr[prizedIndex]).toString());
record.setStatus(0);
lotteryRecordManager.saveOrUpdateByApi(record);
}
resp.getBody().put("data", Arrays.asList(arr[prizedIndex]));
}
resp.setRetcode("200");
resp.setRetmesg("请求成功");
return resp;
}

posted @ 2018-12-07 15:08  9102_Struggle  阅读(549)  评论(0编辑  收藏  举报