项目开发中经常会有抽奖如许的营销活动的需求,例如:积分大转盘、刮刮乐、LH机等等多种形式,其实后台的实现办法是一样的,本文介绍一种常用的抽奖实现办法。
整个抽奖过程包罗以下几个方面:
奖品奖品池抽奖算法奖品限造奖品发放奖品 奖品包罗奖品、奖品概率和限造、奖品记录。奖品表:
CREATE TABLE `points_luck_draw_prize` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`name` varchar(50) DEFAULT NULL COMMENT '奖品名称',`url` varchar(50) DEFAULT NULL COMMENT '图片地址',`value` varchar(20) DEFAULT NULL,`type` tinyint(4) DEFAULT NULL COMMENT '类型1:红包2:积分3:体验金4:谢谢光顾5:自定义',`status` tinyint(4) DEFAULT NULL COMMENT '形态',`is_del` bit(1) DEFAULT NULL COMMENT '能否删除',`position` int(5) DEFAULT NULL COMMENT '位置',`phase` int(10) DEFAULT NULL COMMENT '期数',`create_time` datetime DEFAULT NULL,`update_time` datetime DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=164 DEFAULT CHARSET=utf8mb4 COMMENT='奖品表';奖品概率限造表:
CREATE TABLE `points_luck_draw_probability` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`points_prize_id` bigint(20) DEFAULT NULL COMMENT '奖品ID',`points_prize_phase` int(10) DEFAULT NULL COMMENT '奖品期数',`probability` float(4,2) DEFAULT NULL COMMENT '概率',`frozen` int(11) DEFAULT NULL COMMENT '商品抽中后的冷冻次数',`prize_day_max_times` int(11) DEFAULT NULL COMMENT '该商品平台每天最多抽中的次数',`user_prize_month_max_times` int(11) DEFAULT NULL COMMENT '每位用户每月最多抽中该商品的次数',`create_time` datetime DEFAULT NULL,`update_time` datetime DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=114 DEFAULT CHARSET=utf8mb4 COMMENT='抽奖概率限造表';奖品记录表:
CREATE TABLE `points_luck_draw_record` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`member_id` bigint(20) DEFAULT NULL COMMENT '用户ID',`member_mobile` varchar(11) DEFAULT NULL COMMENT '中奖用户手机号',`points` int(11) DEFAULT NULL COMMENT '消耗积分',`prize_id` bigint(20) DEFAULT NULL COMMENT '奖品ID',`result` smallint(4) DEFAULT NULL COMMENT '1:中奖 2:未中奖',`month` varchar(10) DEFAULT NULL COMMENT '中奖月份',`daily` date DEFAULT NULL COMMENT '中奖日期(不包罗时间)',`create_time` datetime DEFAULT NULL,`update_time` datetime DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3078 DEFAULT CHARSET=utf8mb4 COMMENT='抽奖记录表';奖品池奖品池是按照奖品的概率和限造组拆成的抽奖用的池子。次要包罗奖品的总池值和每个奖品所占的池值(分为起头值和完毕值)两个维度。
奖品的总池值:所有奖品池值的总和。
每个奖品的池值:算法能够变通,常用的有以下两种体例 :
奖品的概率*10000(包管是整数)奖品的概率10000奖品的剩余数量奖品池bean:
public class PrizePool implements Serializable{private int total;private List<PrizePoolBean> poolBeanList;}池中的奖品bean:
public class PrizePoolBean implements Serializable{private Long id;private int begin;private int end;}奖品池的组拆代码:
private PrizePool getZillionairePrizePool(Map<Long, ActivityProduct> zillionaireProductMap, boolean flag) {//总的奖品池值int total = 0;List<PrizePoolBean> poolBeanList = new ArrayList<>();for(Entry<Long, ActivityProduct> entry : zillionaireProductMap.entrySet()){ActivityProduct product = entry.getValue();//无现金奖品池,过滤掉类型为现金的奖品if(!flag && product.getCategoryId() == ActivityPrizeTypeEnums.XJ.getType()){continue;}//组拆奖品池奖品PrizePoolBean prizePoolBean = new PrizePoolBean();prizePoolBean.setId(product.getProductDescriptionId());prizePoolBean.setBengin(total);total = total + product.getEarnings().multiply(new BigDecimal("10000")).intValue();prizePoolBean.setEnd(total);poolBeanList.add(prizePoolBean);}PrizePool prizePool = new PrizePool();prizePool.setTotal(total);prizePool.setPoolBeanList(poolBeanList);return prizePool;}抽奖算法整个抽奖算法为:
随机奖品池总池值以内的整数轮回比力奖品池中的所有奖品,随机数落到哪个奖品的池区间即为哪个奖品中奖。抽奖代码:
public static PrizePoolBean getPrize(PrizePool prizePool){//获取总的奖品池值int total = prizePool.getTotal();//获取随机数Random rand=new Random();int random=rand.nextInt(total);//轮回比力奖品池区间for(PrizePoolBean prizePoolBean : prizePool.getPoolBeanList()){if(random >= prizePoolBean.getBengin() && random < prizePoolBean.getEnd()){return prizePoolBean;}}return null;}奖品限造现实抽奖中对一些比力大的奖品往往有数量限造,好比:某某奖品一天最多被抽中5次、某某奖品每位用户只能抽中一次。。等等类似的限造,关于如许的限造我们分为两种情况来区别看待:
限造的奖品比力少,凡是不多于3个:那种情况我们能够再组拆奖品池的时候就把不契合前提的奖品过滤掉,如许抽中的奖品都是契合前提的。例如,在上面的超等豪富翁抽奖代码中,我们规定现金奖品一天只能被抽中5次,那么我们能够按照判断前提别离组拆出有现金的奖品和没有现金的奖品。限造的奖品比力多,如许若是要接纳第一种体例,就会招致组拆奖品十分繁琐,性能低下,我们能够接纳抽中奖品后校验抽中的奖品能否契合前提,若是不契合前提则返回一个固定的奖品即可。奖品发放奖品发放能够接纳工场形式停止发放:差别的奖品类型走差别的奖品发放处置器,示例代码如下:
奖品发放:
@Async("myAsync")@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)public Future<Boolean> sendPrize(Long memberId, List<PrizeDto> prizeList){try {for(PrizeDto prizeDto : prizeList){//过滤掉谢谢光顾的奖品if(prizeDto.getType() == PointsLuckDrawTypeEnum.XXHG.getType()){continue;}//按照奖品类型从工场中获取奖品发放类SendPrizeProcessor sendPrizeProcessor = sendPrizeProcessorFactory.getSendPrizeProcessor(PointsLuckDrawTypeEnum.getPointsLuckDrawTypeEnumByType(prizeDto.getType()));if(ObjectUtil.isNotNull(sendPrizeProcessor)){//发放奖品sendPrizeProcessor.send(memberId, prizeDto);}}return new AsyncResult<>(Boolean.TRUE);}catch (Exception e){//奖品发放失败则记录日记saveSendPrizeErrorLog(memberId, prizeList);LOGGER.error("积分抽奖发放奖品呈现异常", e);return new AsyncResult<>(Boolean.FALSE);}}工场类:
@Componentpublic class SendPrizeProcessorFactory implements ApplicationContextAware{private ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}public SendPrizeProcessor getSendPrizeProcessor(PointsLuckDrawTypeEnum typeEnum){String processorName = typeEnum.getSendPrizeProcessorName();if(StrUtil.isBlank(processorName)){return null;}SendPrizeProcessor processor = applicationContext.getBean(processorName, SendPrizeProcessor.class);if(ObjectUtil.isNull(processor)){throw new RuntimeException("没有找到名称为【" + processorName + "】的发送奖品处置器");}return processor;}}奖品发放类举例:
@Component("sendHbPrizeProcessor")public class SendHbPrizeProcessor implements SendPrizeProcessor{private Logger LOGGER = LoggerFactory.getLogger(SendHbPrizeProcessor.class);@Resourceprivate CouponService couponService;@Resourceprivate MessageLogService messageLogService;@Overridepublic void send(Long memberId, PrizeDto prizeDto) throws Exception {// 发放红包Coupon coupon = couponService.receiveCoupon(memberId, Long.parseLong(prizeDto.getValue()));//发送站内信messageLogService.insertActivityMessageLog(memberId,"你参与积分抽大奖活动抽中的" + coupon.getAmount() + "元理财红包已到账,谢谢参与","积分抽大奖中奖通知");//输出log日记LOGGER.info(memberId + "在积分抽奖中抽中的" + prizeDto.getPrizeName() + "已经发放!");}}原文链接:https://blog.csdn.net/wang258533488/article/details/78901303
版权声明:本文为CSDN博主「秦霜」的原创文章,遵照CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
近期热文保举:
1.1,000+ 道 Java面试题及谜底整理(2022最新版)
2.劲爆!Java 协程要来了。。。
3.Spring Boot 2.x 教程,太全了!
4.别再写满屏的爆爆爆炸类了,尝尝粉饰器形式,那才是文雅的体例!!
5.《Java开发手册(嵩山版)》最新发布,速速下载!
觉得不错,别忘了随手点赞+转发哦!






还没有评论,来说两句吧...