この記事では、主にJavaの宝くじ機能を詳しく紹介します。この記事のサンプルコードは非常に詳細で、特定の参照値があります。興味のある友人はそれを参照できます。
この記事の例では、参考のためにJavaで宝くじ機能を実装するための特定のコードを共有しています。具体的な内容は次のとおりです。
1。概要
プロジェクト開発では、ポイントカルーセル、スクラッチオフ、スロットマシンなど、宝くじなどのマーケティング活動が必要になることがよくあります。実際、背景の実装方法は同じです。この記事では、一般的に使用される方法を紹介します。宝くじの実装。
宝くじのプロセス全体には、次の側面が含まれます。
- 賞
- 賞金プール
- 宝くじアルゴリズム
- 賞品の制限
- 賞品の配布
2つの賞品
賞品には、賞品、賞品の確率と制限、および賞品の記録が含まれます。
賞金表:
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='抽奖记录表';
3賞金プール
賞金プールは、賞品の確率と制限に従って組み立てられた宝くじプールです。これには主に、賞品の合計プール値と、各賞品が占めるプール値(開始値と終了値に分割)の2つのディメンションが含まれます。
賞金プールの合計値:すべての賞金プールの値の合計。
各賞のプール値:アルゴリズムは柔軟であり、次の2つの方法が一般的に使用されます:
1)賞の確率* 10000(整数であることが保証されます)
2)賞の確率10000残りの賞の数
賞金プール豆:
public class PrizePool implements Serializable{
/**
* 总池值
*/
private int total;
/**
* 池中的奖品
*/
private List<PrizePoolBean> poolBeanList;
}
プール内のプライズビーンズ:
public class PrizePoolBean implements Serializable{
/**
* 数据库中真实奖品的ID
*/
private Long id;
/**
* 奖品的开始池值
*/
private int begin;
/**
* 奖品的结束池值
*/
private int end;
}
賞金プールのアセンブリコード:
/**
* 获取超级大富翁的奖品池
* @param zillionaireProductMap 超级大富翁奖品map
* @param flag true:有现金 false:无现金
* @return
*/
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;
}
4宝くじアルゴリズム
宝くじのアルゴリズム全体は次のとおりです。
- ランダム賞金プールの合計値内の整数
- 賞金プール内のすべての賞品をラウンドロビン方式で比較すると、乱数は賞品である賞金プールの範囲に含まれます。
ラッキードローコード:
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賞品の制限
実際の抽選では、比較的大きな賞品の数に制限があることがよくあります。たとえば、特定の賞品は1日5回まで抽選でき、各ユーザーは特定の賞品に対して1回しか抽選できません。。同様の制限については、そのような制限を2つの状況に分けて、それらを異なる方法で処理します。
- 制限された賞品は比較的少なく、通常は3つ以下です。この場合、賞品プールを再構成するときに、資格のない賞品を除外して、抽選された賞品が対象となるようにすることができます。例えば、上記の超独占宝くじのコードでは、賞金は1日5回しか抽選できないと規定しており、審査条件に応じて賞金と現金なしの賞品を集めることができます。
- 制限された賞品が多いため、最初の方法を使用すると、賞品の組み立てが非常に面倒になり、パフォーマンスが低下します。賞品を使用して、賞品が条件を満たしているかどうかを確認できます。条件を満たしていない場合は、1つ返品してください。固定の賞品で十分です。
6賞金の分配
賞品はファクトリモードで配布できます。賞品の種類が異なれば、賞品配布プロセッサも異なります。サンプルコードは次のとおりです。
賞品の配布:
/**
* 异步分发奖品
* @param prizeList
* @throws Exception
*/
@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);
}
}
ファクトリクラス:
@Component
public class SendPrizeProcessorFactory implements ApplicationContextAware{
private ApplicationContext applicationContext;
@Override
public 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);
@Resource
private CouponService couponService;
@Resource
private MessageLogService messageLogService;
@Override
public 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() + "已经发放!");
}
}
以上が本稿の内容ですので、皆様のご勉強に役立てていただければ幸いです。