/** * * @param request 盲盒抽奖 * @param request * @return */ @Override public BGitf lotteryResults(HttpServletRequest request) { BUserInfo userInfo = ibUserInfoService.validationToken(request); Long id = userInfo.getId(); String phoneNum = userInfo.getPhoneNum(); String nickName = userInfo.getNickName(); String isNewUser = userInfo.getIsNewUser(); Assert.isTrue(isNewUser.equals("1"), "抱歉,您不是新用户"); List<BGitf> bGitfs = bGitfMapper.selectBGitfList( new BGitf()); BGitf bGitf = mainWeightRandom(bGitfs); Long gitfId = bGitf.getGitfId(); String gitfName = bGitf.getGitfName(); String gitfImge = bGitf.getGitfImge(); BUserAwardRecord bUserAwardRecord = new BUserAwardRecord(); bUserAwardRecord.setUserId(id); bUserAwardRecord.setAwardId(gitfId); bUserAwardRecord.setAwardName(gitfName); bUserAwardRecord.setGitImge(gitfImge); bUserAwardRecord.setUserName(nickName); bUserAwardRecord.setUserPhone(phoneNum); bUserAwardRecord.setCreateTime(new Date()); bUserAwardRecordMapper.insertBUserAwardRecord(bUserAwardRecord); isNewUser = "1"; userInfo.setIsNewUser(isNewUser); bUserInfoMapper.updateBUserInfo(userInfo); String token = UUID.randomUUID().toString(); redisTemplate.opsForValue().set(token, JSON.toJSONString(userInfo),5, TimeUnit.HOURS); return bGitf; } /** * 抽奖方法 * @param awardEntities * @return */ // 权重主方法 public static BGitf mainWeightRandom(List<BGitf> awardEntities) { Integer weightSum = 0; //计算总权重 for (BGitf wc : awardEntities) { weightSum += wc.getGitfProbability(); } if (weightSum <= 0) { return null; } // n in [0, weightSum) //产生一个[0, weightSum) 的随机数 Random random = new Random(); Integer n = random.nextInt(weightSum); //判断在那个权重区间 Integer m = 0; for (BGitf wc : awardEntities) { if (m <= n && n < m + wc.getGitfProbability()) { return wc; } m += wc.getGitfProbability(); } return null; }