一、从奖品列表中按奖品中奖概率选中一个作为中奖奖品
private LuckyAward draw(Long activityId) {
//获取抽奖奖品列表
List<LuckyAward> luckyAwards = luckyAwardService.listLuckyAward(activityId);
if (null == luckyAwards || luckyAwards.size() == 0) {
throw new Exception("奖品发完");
}
List<WeightRandom.WeightObj<LuckyAward>> weightObjs = new ArrayList<>();
//安慰奖,不限量
LuckyAward defaultAward = null;
Optional<LuckyAward> defaultAwardOpt = luckyAwards.stream().filter(f -> f.getComfort()).findFirst();
if (defaultAwardOpt.isPresent()) {
defaultAward = defaultAwardOpt.get();
}
luckyAwards.forEach(award -> {
weightObjs.add(new WeightRandom.WeightObj<>(award, award.getProbability()));
});
if (weightObjs.size() == 0) {
throw new Exception("奖品发完");
}
//从奖品列表中按奖品中奖概率选中一个作为中奖奖品
WeightRandom random = RandomUtil.weightRandom(weightObjs);
LuckyAward award = (LuckyAward) random.next();
if (null != awardStockRdsHelper.popAward(award.getId())) {
return award;
} else {
if (null == defaultAward) {
throw new Exception("奖品发完");
}
return defaultAward;
}
}
奖品对象
public class LuckyAward extends BaseModel<LuckyAward> {
/**
* 抽奖活动ID
*/
private Long activityId;
/**
* 奖品编号
*/
private String awardNo;
/**
* 奖品等级
*/
private String awardGrade;
/**
* 奖品类型
*/
private AwardTypeEnum awardType;
/**
* 奖品名称
*/
private String awardName;
/**
* 图片地址
*/
private String imageUrl;
/**
* 奖品价值
*/
private String worth;
/**
* 奖品数量
*/
private Integer awardNumber;
/**
* 已发放数
*/
private Integer grandNumber;
/**
* 中奖概率
*/
private Double probability;
/**
* 排序序号
*/
private Integer orderNumber;
/**
* 是否为安慰奖
*/
private Boolean comfort;
}