code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
package org.example.domain.strategy.model.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.example.types.common.Constants;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 策略实体
* @create 2023-12-31 15:24
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StrategyEntity {
/** 抽奖策略ID */
private Long strategyId;
/** 抽奖策略描述 */
private String strategyDesc;
/** 抽奖规则模型 rule_weight,rule_blacklist */
private String ruleModels;
public String[] ruleModels() {
if (StringUtils.isBlank(ruleModels)) return null;
return ruleModels.split(Constants.SPLIT);
}
public String getRuleWeight() {
String[] ruleModels = this.ruleModels();
if (null == ruleModels) return null;
for (String ruleModel : ruleModels) {
if ("rule_weight".equals(ruleModel)) return ruleModel;
}
return null;
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/model/entity/StrategyEntity.java
|
Java
|
unknown
| 1,086
|
package org.example.domain.strategy.model.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.example.types.common.Constants;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 策略规则实体
* @create 2023-12-31 15:32
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StrategyRuleEntity {
/** 抽奖策略ID */
private Long strategyId;
/** 抽奖奖品ID【规则类型为策略,则不需要奖品ID】 */
private Integer awardId;
/** 抽象规则类型;1-策略规则、2-奖品规则 */
private Integer ruleType;
/** 抽奖规则类型【rule_random - 随机值计算、rule_lock - 抽奖几次后解锁、rule_luck_award - 幸运奖(兜底奖品)】 */
private String ruleModel;
/** 抽奖规则比值 */
private String ruleValue;
/** 抽奖规则描述 */
private String ruleDesc;
/**
* 获取权重值
* 数据案例;4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
*/
public Map<String, List<Integer>> getRuleWeightValues() {
if (!"rule_weight".equals(ruleModel)) return null;
String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
Map<String, List<Integer>> resultMap = new HashMap<>();
for (String ruleValueGroup : ruleValueGroups) {
// 检查输入是否为空
if (ruleValueGroup == null || ruleValueGroup.isEmpty()) {
return resultMap;
}
// 分割字符串以获取键和值
String[] parts = ruleValueGroup.split(Constants.COLON);
if (parts.length != 2) {
throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
}
// 解析值
String[] valueStrings = parts[1].split(org.example.types.common.Constants.SPLIT);
List<Integer> values = new ArrayList<>();
for (String valueString : valueStrings) {
values.add(Integer.parseInt(valueString));
}
// 将键和值放入Map中
resultMap.put(ruleValueGroup, values);
}
return resultMap;
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/model/entity/StrategyRuleEntity.java
|
Java
|
unknown
| 2,395
|
package org.example.domain.strategy.model.valobj;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则限定枚举值
* @create 2024-01-27 12:27
*/
@Getter
@AllArgsConstructor
public enum RuleLimitTypeVO {
EQUAL(1, "等于"),
GT(2, "大于"),
LT(3, "小于"),
GE(4, "大于&等于"),
LE(5, "小于&等于"),
ENUM(6, "枚举"),
;
private final Integer code;
private final String info;
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/model/valobj/RuleLimitTypeVO.java
|
Java
|
unknown
| 504
|
package org.example.domain.strategy.model.valobj;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则过滤校验类型值对象
* @create 2024-01-06 11:10
*/
@Getter
@AllArgsConstructor
public enum RuleLogicCheckTypeVO {
ALLOW("0000", "放行;执行后续的流程,不受规则引擎影响"),
TAKE_OVER("0001","接管;后续的流程,受规则引擎执行结果影响"),
;
private final String code;
private final String info;
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/model/valobj/RuleLogicCheckTypeVO.java
|
Java
|
unknown
| 541
|
package org.example.domain.strategy.model.valobj;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则树节点指向线对象。用于衔接 from->to 节点链路关系
* @create 2024-01-27 10:49
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RuleTreeNodeLineVO {
/** 规则树ID */
private String treeId;
/** 规则Key节点 From */
private String ruleNodeFrom;
/** 规则Key节点 To */
private String ruleNodeTo;
/** 限定类型;1:=;2:>;3:<;4:>=;5<=;6:enum[枚举范围] */
private RuleLimitTypeVO ruleLimitType;
/** 限定值(到下个节点) */
private RuleLogicCheckTypeVO ruleLimitValue;
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/model/valobj/RuleTreeNodeLineVO.java
|
Java
|
unknown
| 803
|
package org.example.domain.strategy.model.valobj;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则树节点对象
* @create 2024-01-27 10:48
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RuleTreeNodeVO {
/** 规则树ID */
private String treeId;
/** 规则Key */
private String ruleKey;
/** 规则描述 */
private String ruleDesc;
/** 规则比值 */
private String ruleValue;
/** 规则连线 */
private List<RuleTreeNodeLineVO> treeNodeLineVOList;
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/model/valobj/RuleTreeNodeVO.java
|
Java
|
unknown
| 681
|
package org.example.domain.strategy.model.valobj;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Map;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则树对象【注意;不具有唯一ID,不需要改变数据库结果的对象,可以被定义为值对象】
* @create 2024-01-27 10:45
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RuleTreeVO {
/** 规则树ID */
private String treeId;
/** 规则树名称 */
private String treeName;
/** 规则树描述 */
private String treeDesc;
/** 规则根节点 */
private String treeRootRuleNode;
/** 规则节点 */
private Map<String, RuleTreeNodeVO> treeNodeMap;
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/model/valobj/RuleTreeVO.java
|
Java
|
unknown
| 790
|
package org.example.domain.strategy.model.valobj;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.example.types.common.Constants;
import java.util.ArrayList;
import java.util.List;
/**
* @author yk
* @description :抽奖策略规则规则值对象;值对象,没有唯一ID,仅限于从数据库查询对象
* @create 2024-03-12 19-26
*/
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StrategyAwardRuleModelVO {
private String ruleModels;
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/model/valobj/StrategyAwardRuleModelVO.java
|
Java
|
unknown
| 556
|
package org.example.domain.strategy.model.valobj;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* @author @yk
* @description :策略奖品库存key标识值对象
* @create 2024-03-14 20:29
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StrategyAwardStockKeyVO {
//策略ID
private Long strategyId;
//奖品ID
private Integer awardId;
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/model/valobj/StrategyAwardStockKeyVO.java
|
Java
|
unknown
| 487
|
package org.example.domain.strategy.repository;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import org.example.domain.strategy.model.entity.StrategyEntity;
import org.example.domain.strategy.model.entity.StrategyRuleEntity;
import org.example.domain.strategy.model.valobj.RuleTreeVO;
import org.example.domain.strategy.model.valobj.StrategyAwardRuleModelVO;
import org.example.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import java.util.List;
import java.util.Map;
/**
* 策略仓储
*/
public interface IStrategyRepository {
List<StrategyAwardEntity> queryStrategyAwardList(Long strategyId);
void storeStrategyAwardSearchRateTable(String key, Integer rateRange, Map<Integer, Integer> strategyAwardSearchRateTable);
int getRateRange(Long strategyId);
int getRateRange(String key);
Integer getStrategyAwardAssemble(String key, Integer rateKey);
StrategyEntity queryStrategyEntityByStrategyId(Long strategyId);
StrategyRuleEntity queryStrategyRule(Long strategyId, String ruleModel);
String queryStrategyRuleValue(Long strategyId, Integer awardId, String ruleModel);
String queryStrategyRuleValue(Long strategyId, String ruleModel);
StrategyAwardRuleModelVO queryStrategyAwardRuleModelVO(Long strategyId, Integer awardId);
/**
* 根据规则树ID,查询树结构信息
*
* @param treeId 规则树ID
* @return 树结构信息
*/
RuleTreeVO queryRuleTreeVOByTreeId(String treeId);
/**
* 缓存奖品库存
*
* @param cacheKey key
* @param awardCount 库存值
*/
void cacheStrategyAwardCount(String cacheKey, Integer awardCount);
/**
* 缓存key,decr 方式扣减库存
*
* @param cacheKey 缓存Key
* @return 扣减结果
*/
Boolean subtractionAwardStock(String cacheKey);
void awardStockConsumeSendQueue(StrategyAwardStockKeyVO strategyAwardStockKeyVO);
StrategyAwardStockKeyVO takeQueueValue();
void updateStrategyAwardStock(Long strategyId, Integer awardId);
/**
* 根据策略ID+奖品ID的唯一值组合,查询奖品信息
*
* @param strategyId 策略ID
* @param awardId 奖品ID
* @return 奖品信息
*/
StrategyAwardEntity queryStrategyAwardEntity(Long strategyId, Integer awardId);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/repository/IStrategyRepository.java
|
Java
|
unknown
| 2,347
|
package org.example.domain.strategy.service;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.domain.strategy.model.entity.RaffleAwardEntity;
import org.example.domain.strategy.model.entity.RaffleFactorEntity;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 抽奖策略抽象类,定义抽奖的标准流程
* @create 2024-01-06 09:26
*/
@Slf4j
public abstract class AbstractRaffleStrategy implements IRaffleStrategy {
// 策略仓储服务 -> domain层像一个大厨,仓储层提供米面粮油
protected IStrategyRepository repository;
// 策略调度服务 -> 只负责抽奖处理,通过新增接口的方式,隔离职责,不需要使用方关心或者调用抽奖的初始化
protected IStrategyDispatch strategyDispatch;
// 抽奖的责任链 -> 从抽奖的规则中,解耦出前置规则为责任链处理
protected final DefaultChainFactory defaultChainFactory;
// 抽奖的决策树 -> 负责抽奖中到抽奖后的规则过滤,如抽奖到A奖品ID,之后要做次数的判断和库存的扣减等。
protected final DefaultTreeFactory defaultTreeFactory;
public AbstractRaffleStrategy(IStrategyRepository repository, IStrategyDispatch strategyDispatch, DefaultChainFactory defaultChainFactory, DefaultTreeFactory defaultTreeFactory) {
this.repository = repository;
this.strategyDispatch = strategyDispatch;
this.defaultChainFactory = defaultChainFactory;
this.defaultTreeFactory = defaultTreeFactory;
}
@Override
public RaffleAwardEntity performRaffle(RaffleFactorEntity raffleFactorEntity) {
// 1. 参数校验
String userId = raffleFactorEntity.getUserId();
Long strategyId = raffleFactorEntity.getStrategyId();
if (null == strategyId || StringUtils.isBlank(userId)) {
throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
}
// 2. 责任链抽奖计算【这步拿到的是初步的抽奖ID,之后需要根据ID处理抽奖】注意;黑名单、权重等非默认抽奖的直接返回抽奖结果
DefaultChainFactory.StrategyAwardVO chainStrategyAwardVO = raffleLogicChain(userId, strategyId);
log.info("抽奖策略计算-责任链 {} {} {} {}", userId, strategyId, chainStrategyAwardVO.getAwardId(), chainStrategyAwardVO.getLogicModel());
if (!DefaultChainFactory.LogicModel.RULE_DEFAULT.getCode().equals(chainStrategyAwardVO.getLogicModel())) {
// TODO awardConfig 暂时为空。黑名单指定积分奖品,后续需要在库表中配置上对应的1积分值,并获取到。
return buildRaffleAwardEntity(strategyId, chainStrategyAwardVO.getAwardId(), null);
}
// 3. 规则树抽奖过滤【奖品ID,会根据抽奖次数判断、库存判断、兜底兜里返回最终的可获得奖品信息】
DefaultTreeFactory.StrategyAwardVO treeStrategyAwardVO = raffleLogicTree(userId, strategyId, chainStrategyAwardVO.getAwardId());
log.info("抽奖策略计算-规则树 {} {} {} {}", userId, strategyId, treeStrategyAwardVO.getAwardId(), treeStrategyAwardVO.getAwardRuleValue());
// 4. 返回抽奖结果
return buildRaffleAwardEntity(strategyId, treeStrategyAwardVO.getAwardId(), treeStrategyAwardVO.getAwardRuleValue());
}
private RaffleAwardEntity buildRaffleAwardEntity(Long strategyId, Integer awardId, String awardConfig) {
StrategyAwardEntity strategyAward = repository.queryStrategyAwardEntity(strategyId, awardId);
return RaffleAwardEntity.builder()
.awardId(awardId)
.awardConfig(awardConfig)
.sort(strategyAward.getSort())
.build();
}
/**
* 抽奖计算,责任链抽象方法
*
* @param userId 用户ID
* @param strategyId 策略ID
* @return 奖品ID
*/
public abstract DefaultChainFactory.StrategyAwardVO raffleLogicChain(String userId, Long strategyId);
/**
* 抽奖结果过滤,决策树抽象方法
*
* @param userId 用户ID
* @param strategyId 策略ID
* @param awardId 奖品ID
* @return 过滤结果【奖品ID,会根据抽奖次数判断、库存判断、兜底兜里返回最终的可获得奖品信息】
*/
public abstract DefaultTreeFactory.StrategyAwardVO raffleLogicTree(String userId, Long strategyId, Integer awardId);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/AbstractRaffleStrategy.java
|
Java
|
unknown
| 5,013
|
package org.example.domain.strategy.service;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import java.util.List;
/**
* @author @yk
* @description :策略奖品接口
* @create 2024-03-15 22:26
*/
public interface IRaffleAward {
/**
* 根据策略ID查询抽奖奖品列表配置
*
* @param strategyId 策略ID
* @return 奖品列表
*/
List<StrategyAwardEntity> queryRaffleStrategyAwardList(Long strategyId);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/IRaffleAward.java
|
Java
|
unknown
| 477
|
package org.example.domain.strategy.service;
import org.example.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
/**
* @author @yk
* @description :抽奖库存相关服务,获取库存消耗队列
* @create 2024-03-14 20:49
*/
public interface IRaffleStock {
/**
* 获取奖品库存消耗队列
*
* @return 奖品库存Key信息
* @throws InterruptedException 异常
*/
StrategyAwardStockKeyVO takeQueueValue() throws InterruptedException;
/**
* 更新奖品库存消耗记录
*
* @param strategyId 策略ID
* @param awardId 奖品ID
*/
void updateStrategyAwardStock(Long strategyId, Integer awardId);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/IRaffleStock.java
|
Java
|
unknown
| 690
|
package org.example.domain.strategy.service;
import org.example.domain.strategy.model.entity.RaffleAwardEntity;
import org.example.domain.strategy.model.entity.RaffleFactorEntity;
/**
* 抽奖策略接口
*/
public interface IRaffleStrategy {
RaffleAwardEntity performRaffle(RaffleFactorEntity raffleFactorEntity);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/IRaffleStrategy.java
|
Java
|
unknown
| 326
|
package org.example.domain.strategy.service.armory;
/**
* 策略装配库(兵工厂),负责初始化策略计算
*/
public interface IStrategyArmory {
/**
* 装配抽奖策略配置「触发的时机可以为活动审核通过后进行调用」
*
* @param strategyId 策略ID
* @return 装配结果
*/
boolean assembleLotteryStrategy(Long strategyId);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/armory/IStrategyArmory.java
|
Java
|
unknown
| 398
|
package org.example.domain.strategy.service.armory;
/**
* 策略抽奖调度
*/
public interface IStrategyDispatch {
/**
* 获取抽奖策略装配的随机结果
*
* @param strategyId 策略ID
* @return 抽奖结果
*/
Integer getRandomAwardId(Long strategyId);
/**
* 获取抽奖策略装配的随机结果
*
* @param strategyId 权重ID
* @return 抽奖结果
*/
Integer getRandomAwardId(Long strategyId, String ruleWeightValue);
/**
* 获取抽奖策略装配的随机结果
*
* @param key = strategyId + _ + ruleWeightValue;
* @return 抽奖结果
*/
Integer getRandomAwardId(String key);
/**
* 根据策略ID和奖品ID,扣减奖品缓存库存
*
* @param strategyId 策略ID
* @param awardId 奖品ID
* @return 扣减结果
*/
Boolean subtractionAwardStock(Long strategyId, Integer awardId);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/armory/IStrategyDispatch.java
|
Java
|
unknown
| 952
|
package org.example.domain.strategy.service.armory;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import org.example.domain.strategy.model.entity.StrategyEntity;
import org.example.domain.strategy.model.entity.StrategyRuleEntity;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.types.common.Constants;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;
/**
* @description 策略装配库(兵工厂),负责初始化策略计算
*/
@Slf4j
@Service
public class StrategyArmoryDispatch implements IStrategyArmory, IStrategyDispatch {
@Resource
private IStrategyRepository repository;
private final SecureRandom secureRandom = new SecureRandom();
@Override
public boolean assembleLotteryStrategy(Long strategyId) {
// 1. 查询策略配置
List<StrategyAwardEntity> strategyAwardEntities = repository.queryStrategyAwardList(strategyId);
// 2 缓存奖品库存【用于decr扣减库存使用】
for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
Integer awardId = strategyAward.getAwardId();
Integer awardCount = strategyAward.getAwardCount();
cacheStrategyAwardCount(strategyId, awardId, awardCount);
}
// 3.1 默认装配配置【全量抽奖概率】
assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);
// 3.2 权重策略配置 - 适用于 rule_weight 权重规则配置【4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109】
StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
String ruleWeight = strategyEntity.getRuleWeight();
if (null == ruleWeight) return true;
StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId, ruleWeight);
// 业务异常,策略规则中 rule_weight 权重规则已适用但未配置
if (null == strategyRuleEntity) {
throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
}
Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
for (String key : ruleWeightValueMap.keySet()) {
List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));
assembleLotteryStrategy(String.valueOf(strategyId).concat(Constants.UNDERLINE).concat(key), strategyAwardEntitiesClone);
}
return true;
}
/**
* 计算公式;
* 1. 找到范围内最小的概率值,比如 0.1、0.02、0.003,需要找到的值是 0.003
* 2. 基于1找到的最小值,0.003 就可以计算出百分比、千分比的整数值。这里就是1000
* 3. 那么「概率 * 1000」分别占比100个、20个、3个,总计是123个
* 4. 后续的抽奖就用123作为随机数的范围值,生成的值100个都是0.1概率的奖品、20个是概率0.02的奖品、最后是3个是0.003的奖品。
*/
private void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities) {
// 1. 获取最小概率值
BigDecimal minAwardRate = strategyAwardEntities.stream()
.map(StrategyAwardEntity::getAwardRate)
.min(BigDecimal::compareTo)
.orElse(BigDecimal.ZERO);
// 2. 循环计算找到概率范围值
BigDecimal rateRange = BigDecimal.valueOf(convert(minAwardRate.doubleValue()));
// 3. 生成策略奖品概率查找表「这里指需要在list集合中,存放上对应的奖品占位即可,占位越多等于概率越高」
List<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
Integer awardId = strategyAward.getAwardId();
BigDecimal awardRate = strategyAward.getAwardRate();
// 计算出每个概率值需要存放到查找表的数量,循环填充
for (int i = 0; i < rateRange.multiply(awardRate).intValue(); i++) {
strategyAwardSearchRateTables.add(awardId);
}
}
// 4. 对存储的奖品进行乱序操作
Collections.shuffle(strategyAwardSearchRateTables);
// 5. 生成出Map集合,key值,对应的就是后续的概率值。通过概率来获得对应的奖品ID
Map<Integer, Integer> shuffleStrategyAwardSearchRateTable = new LinkedHashMap<>();
for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
shuffleStrategyAwardSearchRateTable.put(i, strategyAwardSearchRateTables.get(i));
}
// 6. 存放到 Redis
repository.storeStrategyAwardSearchRateTable(key, shuffleStrategyAwardSearchRateTable.size(), shuffleStrategyAwardSearchRateTable);
}
/**
* 转换计算,只根据小数位来计算。如【0.01返回100】、【0.009返回1000】、【0.0018返回10000】
*/
private double convert(double min) {
double current = min;
double max = 1;
while (current < 1) {
current = current * 10;
max = max * 10;
}
return max;
}
/**
* 缓存奖品库存到Redis
*
* @param strategyId 策略ID
* @param awardId 奖品ID
* @param awardCount 奖品库存
*/
private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
repository.cacheStrategyAwardCount(cacheKey, awardCount);
}
@Override
public Integer getRandomAwardId(Long strategyId) {
// 分布式部署下,不一定为当前应用做的策略装配。也就是值不一定会保存到本应用,而是分布式应用,所以需要从 Redis 中获取。
int rateRange = repository.getRateRange(strategyId);
// 通过生成的随机值,获取概率值奖品查找表的结果
return repository.getStrategyAwardAssemble(String.valueOf(strategyId), secureRandom.nextInt(rateRange));
}
@Override
public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
String key = String.valueOf(strategyId).concat(Constants.UNDERLINE).concat(ruleWeightValue);
return getRandomAwardId(key);
}
@Override
public Integer getRandomAwardId(String key) {
// 分布式部署下,不一定为当前应用做的策略装配。也就是值不一定会保存到本应用,而是分布式应用,所以需要从 Redis 中获取。
int rateRange = repository.getRateRange(key);
// 通过生成的随机值,获取概率值奖品查找表的结果
return repository.getStrategyAwardAssemble(key, secureRandom.nextInt(rateRange));
}
@Override
public Boolean subtractionAwardStock(Long strategyId, Integer awardId) {
String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
return repository.subtractionAwardStock(cacheKey);
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/armory/StrategyArmoryDispatch.java
|
Java
|
unknown
| 7,816
|
package org.example.domain.strategy.service.raffle;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import org.example.domain.strategy.model.valobj.RuleTreeVO;
import org.example.domain.strategy.model.valobj.StrategyAwardRuleModelVO;
import org.example.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.AbstractRaffleStrategy;
import org.example.domain.strategy.service.IRaffleAward;
import org.example.domain.strategy.service.IRaffleStock;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.chain.ILogicChain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.example.domain.strategy.service.rule.tree.factory.engine.IDecisionTreeEngine;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 默认抽奖实现
*/
@Slf4j
@Service
public class DefaultRaffleStrategy extends AbstractRaffleStrategy implements IRaffleAward , IRaffleStock {
public DefaultRaffleStrategy(IStrategyRepository repository, IStrategyDispatch strategyDispatch, DefaultChainFactory defaultChainFactory, DefaultTreeFactory defaultTreeFactory) {
super(repository, strategyDispatch, defaultChainFactory, defaultTreeFactory);
}
@Override
public DefaultChainFactory.StrategyAwardVO raffleLogicChain(String userId, Long strategyId) {
ILogicChain logicChain = defaultChainFactory.openLogicChain(strategyId);
return logicChain.logic(userId, strategyId);
}
@Override
public DefaultTreeFactory.StrategyAwardVO raffleLogicTree(String userId, Long strategyId, Integer awardId) {
StrategyAwardRuleModelVO strategyAwardRuleModelVO = repository.queryStrategyAwardRuleModelVO(strategyId, awardId);
if (null == strategyAwardRuleModelVO) {
return DefaultTreeFactory.StrategyAwardVO.builder().awardId(awardId).build();
}
RuleTreeVO ruleTreeVO = repository.queryRuleTreeVOByTreeId(strategyAwardRuleModelVO.getRuleModels());
if (null == ruleTreeVO) {
throw new RuntimeException("存在抽奖策略配置的规则模型 Key,未在库表 rule_tree、rule_tree_node、rule_tree_line 配置对应的规则树信息 " + strategyAwardRuleModelVO.getRuleModels());
}
IDecisionTreeEngine treeEngine = defaultTreeFactory.openLogicTree(ruleTreeVO);
return treeEngine.process(userId, strategyId, awardId);
}
@Override
public StrategyAwardStockKeyVO takeQueueValue() throws InterruptedException {
return repository.takeQueueValue();
}
@Override
public void updateStrategyAwardStock(Long strategyId, Integer awardId) {
repository.updateStrategyAwardStock(strategyId, awardId);
}
@Override
public List<StrategyAwardEntity> queryRaffleStrategyAwardList(Long strategyId) {
return repository.queryStrategyAwardList(strategyId);
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/raffle/DefaultRaffleStrategy.java
|
Java
|
unknown
| 3,167
|
package org.example.domain.strategy.service.rule.chain;
import lombok.extern.slf4j.Slf4j;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 抽奖策略责任链,判断走那种抽奖策略。如;默认抽象、权重抽奖、黑名单抽奖
* @create 2024-01-20 09:37
*/
@Slf4j
public abstract class AbstractLogicChain implements ILogicChain {
private ILogicChain next;
@Override
public ILogicChain next() {
return next;
}
@Override
public ILogicChain appendNext(ILogicChain next) {
this.next = next;
return next;
}
protected abstract String ruleModel();
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/chain/AbstractLogicChain.java
|
Java
|
unknown
| 642
|
package org.example.domain.strategy.service.rule.chain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 抽奖策略规则责任链接口
* @create 2024-01-20 09:40
*/
public interface ILogicChain extends ILogicChainArmory{
/**
* 责任链接口
*
* @param userId 用户ID
* @param strategyId 策略ID
* @return 奖品ID
*/
DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/chain/ILogicChain.java
|
Java
|
unknown
| 549
|
package org.example.domain.strategy.service.rule.chain;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 责任链装配
* @create 2024-01-20 11:53
*/
public interface ILogicChainArmory {
ILogicChain next();
ILogicChain appendNext(ILogicChain next);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/chain/ILogicChainArmory.java
|
Java
|
unknown
| 282
|
package org.example.domain.strategy.service.rule.chain.factory;
import lombok.*;
import org.example.domain.strategy.model.entity.StrategyEntity;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.rule.chain.ILogicChain;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 工厂
* @create 2024-01-20 10:54
*/
@Service
public class DefaultChainFactory {
private final Map<String, ILogicChain> logicChainGroup;
protected IStrategyRepository repository;
public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository repository) {
this.logicChainGroup = logicChainGroup;
this.repository = repository;
}
/**
* 通过策略ID,构建责任链
*
* @param strategyId 策略ID
* @return LogicChain
*/
public ILogicChain openLogicChain(Long strategyId) {
StrategyEntity strategy = repository.queryStrategyEntityByStrategyId(strategyId);
String[] ruleModels = strategy.ruleModels();
// 如果未配置策略规则,则只装填一个默认责任链
if (null == ruleModels || 0 == ruleModels.length) return logicChainGroup.get("default");
// 按照配置顺序装填用户配置的责任链;rule_blacklist、rule_weight 「注意此数据从Redis缓存中获取,如果更新库表,记得在测试阶段手动处理缓存」
ILogicChain logicChain = logicChainGroup.get(ruleModels[0]);
ILogicChain current = logicChain;
for (int i = 1; i < ruleModels.length; i++) {
ILogicChain nextChain = logicChainGroup.get(ruleModels[i]);
current = current.appendNext(nextChain);
}
// 责任链的最后装填默认责任链
current.appendNext(logicChainGroup.get("default"));
return logicChain;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class StrategyAwardVO {
/** 抽奖奖品ID - 内部流转使用 */
private Integer awardId;
/** */
private String logicModel;
}
@Getter
@AllArgsConstructor
public enum LogicModel {
RULE_DEFAULT("rule_default", "默认抽奖"),
RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
RULE_WEIGHT("rule_weight", "权重规则"),
;
private final String code;
private final String info;
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/chain/factory/DefaultChainFactory.java
|
Java
|
unknown
| 2,528
|
package org.example.domain.strategy.service.rule.chain.impl;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.example.types.common.Constants;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 黑名单责任链
* @create 2024-01-20 10:23
*/
@Slf4j
@Component("rule_blacklist")
public class BackListLogicChain extends AbstractLogicChain {
@Resource
private IStrategyRepository repository;
@Override
public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
log.info("抽奖责任链-黑名单开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
// 查询规则值配置
String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
String[] splitRuleValue = ruleValue.split(Constants.COLON);
Integer awardId = Integer.parseInt(splitRuleValue[0]);
// 黑名单抽奖判断
String[] userBlackIds = splitRuleValue[1].split(Constants.SPLIT);
for (String userBlackId : userBlackIds) {
if (userId.equals(userBlackId)) {
log.info("抽奖责任链-黑名单接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
return DefaultChainFactory.StrategyAwardVO.builder()
.awardId(awardId)
.logicModel(ruleModel())
.build();
}
}
// 过滤其他责任链
log.info("抽奖责任链-黑名单放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
return next().logic(userId, strategyId);
}
@Override
protected String ruleModel() {
return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/chain/impl/BackListLogicChain.java
|
Java
|
unknown
| 2,122
|
package org.example.domain.strategy.service.rule.chain.impl;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 默认的责任链「作为最后一个链」
* @create 2024-01-20 10:06
*/
@Slf4j
@Component("default")
public class DefaultLogicChain extends AbstractLogicChain {
@Resource
protected IStrategyDispatch strategyDispatch;
@Override
public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
Integer awardId = strategyDispatch.getRandomAwardId(strategyId);
log.info("抽奖责任链-默认处理 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
return DefaultChainFactory.StrategyAwardVO.builder()
.awardId(awardId)
.logicModel(ruleModel())
.build();
}
@Override
protected String ruleModel() {
return DefaultChainFactory.LogicModel.RULE_DEFAULT.getCode() ;
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/chain/impl/DefaultLogicChain.java
|
Java
|
unknown
| 1,321
|
package org.example.domain.strategy.service.rule.chain.impl;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.example.types.common.Constants;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 权重抽奖责任链
* @create 2024-01-20 10:38
*/
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {
@Resource
private IStrategyRepository repository;
@Resource
protected IStrategyDispatch strategyDispatch;
// 根据用户ID查询用户抽奖消耗的积分值,本章节我们先写死为固定的值。后续需要从数据库中查询。
public Long userScore = 0L;
/**
* 权重责任链过滤;
* 1. 权重规则格式;4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
* 2. 解析数据格式;判断哪个范围符合用户的特定抽奖范围
*/
@Override
public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
// 1. 根据用户ID查询用户抽奖消耗的积分值,本章节我们先写死为固定的值。后续需要从数据库中查询。
Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);
if (null == analyticalValueGroup || analyticalValueGroup.isEmpty()) return null;
// 2. 转换Keys值,并默认排序
List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
Collections.sort(analyticalSortedKeys);
// 3. 找出最小符合的值,也就是【4500 积分,能找到 4000:102,103,104,105】、【5000 积分,能找到 5000:102,103,104,105,106,107】
/* 找到最后一个符合的值[如用户传了一个 5900 应该返回正确结果为 5000],如果使用 Lambda findFirst 需要注意使用 sorted 反转结果
* Long nextValue = null;
* for (Long analyticalSortedKeyValue : analyticalSortedKeys) {
* if (userScore >= analyticalSortedKeyValue){
* nextValue = analyticalSortedKeyValue;
* }
* }
* 星球伙伴 @慢慢来 ID 6267 提供
* Long nextValue = analyticalSortedKeys.stream()
* .filter(key -> userScore >= key)
* .max(Comparator.naturalOrder())
* .orElse(null);
*/
Long nextValue = analyticalSortedKeys.stream()
.sorted(Comparator.reverseOrder())
.filter(analyticalSortedKeyValue -> userScore >= analyticalSortedKeyValue)
.findFirst()
.orElse(null);
// 4. 权重抽奖
if (null != nextValue) {
Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
return DefaultChainFactory.StrategyAwardVO.builder()
.awardId(awardId)
.logicModel(ruleModel())
.build();
}
// 5. 过滤其他责任链
log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
return next().logic(userId, strategyId);
}
@Override
protected String ruleModel() {
return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
}
private Map<Long, String> getAnalyticalValue(String ruleValue) {
String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
Map<Long, String> ruleValueMap = new HashMap<>();
for (String ruleValueKey : ruleValueGroups) {
// 检查输入是否为空
if (ruleValueKey == null || ruleValueKey.isEmpty()) {
return ruleValueMap;
}
// 分割字符串以获取键和值
String[] parts = ruleValueKey.split(Constants.COLON);
if (parts.length != 2) {
throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
}
ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
}
return ruleValueMap;
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/chain/impl/RuleWeightLogicChain.java
|
Java
|
unknown
| 4,904
|
package org.example.domain.strategy.service.rule.tree;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
/**
* @author @yk
* @description :定义规则树接口
* @create 2024-03-13 19:28
*/
public interface ILogicTreeNode {
DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/tree/ILogicTreeNode.java
|
Java
|
unknown
| 380
|
package org.example.domain.strategy.service.rule.tree.factory;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.example.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import org.example.domain.strategy.model.valobj.RuleTreeVO;
import org.example.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.example.domain.strategy.service.rule.tree.factory.engine.IDecisionTreeEngine;
import org.example.domain.strategy.service.rule.tree.factory.engine.impl.DecisionTreeEngine;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author @yk
* @description :规则树工厂
* @create 2024-03-13 19:37
*/
@Service
public class DefaultTreeFactory {
private final Map<String, ILogicTreeNode> logicTreeNodeGroup;
//Spring根据注解自动的在构造函数阶段把bin对象实例化注入进来
public DefaultTreeFactory(Map<String, ILogicTreeNode> logicTreeNodeGroup) {
this.logicTreeNodeGroup = logicTreeNodeGroup;
}
public IDecisionTreeEngine openLogicTree(RuleTreeVO ruleTreeVO) {
return new DecisionTreeEngine(ruleTreeVO, logicTreeNodeGroup);
}
/**
* 决策树个动作实习
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class TreeActionEntity {
private RuleLogicCheckTypeVO ruleLogicCheckType;
private StrategyAwardVO strategyAwardVO;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class StrategyAwardVO {
/** 抽奖奖品ID - 内部流转使用 */
private Integer awardId;
/** 抽奖奖品规则 */
private String awardRuleValue;
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/tree/factory/DefaultTreeFactory.java
|
Java
|
unknown
| 1,750
|
package org.example.domain.strategy.service.rule.tree.factory.engine;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
/**
* @author @yk
* @description :规则树组合接口
* @create 2024-03-13 19:48
*/
public interface IDecisionTreeEngine {
DefaultTreeFactory.StrategyAwardVO process(String userId, Long strategyId, Integer awardId);
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/tree/factory/engine/IDecisionTreeEngine.java
|
Java
|
unknown
| 383
|
package org.example.domain.strategy.service.rule.tree.factory.engine.impl;
import org.example.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import org.example.domain.strategy.model.valobj.RuleTreeNodeLineVO;
import org.example.domain.strategy.model.valobj.RuleTreeNodeVO;
import org.example.domain.strategy.model.valobj.RuleTreeVO;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.example.domain.strategy.service.rule.tree.factory.engine.IDecisionTreeEngine;
import java.util.List;
import java.util.Map;
/**
* @author @yk
* @description :决策树引擎
* @create 2024-03-13 19:49
*/
@Slf4j
public class DecisionTreeEngine implements IDecisionTreeEngine {
private final RuleTreeVO ruleTreeVO;
private final Map<String, ILogicTreeNode> logicTreeNodeGroup;
public DecisionTreeEngine(RuleTreeVO ruleTreeVO, Map<String, ILogicTreeNode> logicTreeNodeGroup) {
this.ruleTreeVO = ruleTreeVO;
this.logicTreeNodeGroup = logicTreeNodeGroup;
}
@Override
public DefaultTreeFactory.StrategyAwardVO process(String userId, Long strategyId, Integer awardId) {
DefaultTreeFactory.StrategyAwardVO strategyAwardData = null;
// 获取基础信息
String nextNode = ruleTreeVO.getTreeRootRuleNode();
Map<String, RuleTreeNodeVO> treeNodeMap = ruleTreeVO.getTreeNodeMap();
// 获取起始节点「根节点记录了第一个要执行的规则」
RuleTreeNodeVO ruleTreeNode = treeNodeMap.get(nextNode);
while (null != nextNode) {
// 获取决策节点
ILogicTreeNode logicTreeNode = logicTreeNodeGroup.get(ruleTreeNode.getRuleKey());
String ruleValue = ruleTreeNode.getRuleValue();
// 决策节点计算
DefaultTreeFactory.TreeActionEntity logicEntity = logicTreeNode.logic(userId, strategyId, awardId, ruleValue);
RuleLogicCheckTypeVO ruleLogicCheckTypeVO = logicEntity.getRuleLogicCheckType();
strategyAwardData = logicEntity.getStrategyAwardVO();
log.info("决策树引擎【{}】treeId:{} node:{} code:{}", ruleTreeVO.getTreeName(), ruleTreeVO.getTreeId(), nextNode, ruleLogicCheckTypeVO.getCode());
// 获取下个节点
nextNode = nextNode(ruleLogicCheckTypeVO.getCode(), ruleTreeNode.getTreeNodeLineVOList());
ruleTreeNode = treeNodeMap.get(nextNode);
}
// 返回最终结果
return strategyAwardData;
}
public String nextNode(String matterValue, List<RuleTreeNodeLineVO> treeNodeLineVOList) {
if (null == treeNodeLineVOList || treeNodeLineVOList.isEmpty()) return null;
for (RuleTreeNodeLineVO nodeLine : treeNodeLineVOList) {
if (decisionLogic(matterValue, nodeLine)) {
return nodeLine.getRuleNodeTo();
}
}
return null;
}
public boolean decisionLogic(String matterValue, RuleTreeNodeLineVO nodeLine) {
switch (nodeLine.getRuleLimitType()) {
case EQUAL:
return matterValue.equals(nodeLine.getRuleLimitValue().getCode());
// 以下规则暂时不需要实现
case GT:
case LT:
case GE:
case LE:
default:
return false;
}
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/tree/factory/engine/impl/DecisionTreeEngine.java
|
Java
|
unknown
| 3,450
|
package org.example.domain.strategy.service.rule.tree.impl;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import org.example.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.springframework.stereotype.Component;
/**
* @author @yk
* @description :次数锁节点
* @create 2024-03-13 19:31
*/
@Slf4j
@Component("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTreeNode {
// 用户抽奖次数,后续完成这部分流程开发的时候,从数据库/Redis中读取
private Long userRaffleCount = 10L;
@Override
public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue) {
log.info("规则过滤-次数锁 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
long raffleCount = 0L;
try {
raffleCount = Long.parseLong(ruleValue);
} catch (Exception e) {
throw new RuntimeException("规则过滤-次数锁异常 ruleValue: " + ruleValue + " 配置不正确");
}
// 用户抽奖次数大于规则限定值,规则放行
if (userRaffleCount >= raffleCount) {
return DefaultTreeFactory.TreeActionEntity.builder()
.ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
.build();
}
// 用户抽奖次数小于规则限定值,规则拦截
return DefaultTreeFactory.TreeActionEntity.builder()
.ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
.build();
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/tree/impl/RuleLockLogicTreeNode.java
|
Java
|
unknown
| 1,771
|
package org.example.domain.strategy.service.rule.tree.impl;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import org.example.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.example.types.common.Constants;
import org.springframework.stereotype.Component;
/**
* @author @yk
* @description :兜底奖励节点
* @create 2024-03-13 19:33
*/
@Slf4j
@Component("rule_luck_award")
public class RuleLuckAwardLogicTreeNode implements ILogicTreeNode {
@Override
public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue) {
log.info("规则过滤-兜底奖品 userId:{} strategyId:{} awardId:{} ruleValue:{}", userId, strategyId, awardId, ruleValue);
String[] split = ruleValue.split(Constants.COLON);
if (split.length == 0) {
log.error("规则过滤-兜底奖品,兜底奖品未配置告警 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
throw new RuntimeException("兜底奖品未配置 " + ruleValue);
}
// 兜底奖励配置
Integer luckAwardId = Integer.valueOf(split[0]);
String awardRuleValue = split.length > 1 ? split[1] : "";
// 返回兜底奖品
log.info("规则过滤-兜底奖品 userId:{} strategyId:{} awardId:{} awardRuleValue:{}", userId, strategyId, luckAwardId, awardRuleValue);
return DefaultTreeFactory.TreeActionEntity.builder()
.ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
.strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
.awardId(luckAwardId)
.awardRuleValue(awardRuleValue)
.build())
.build();
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/tree/impl/RuleLuckAwardLogicTreeNode.java
|
Java
|
unknown
| 1,907
|
package org.example.domain.strategy.service.rule.tree.impl;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import org.example.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author @yk
* @description :库存节点
* @create 2024-03-13 19:35
*/
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {
@Resource
private IStrategyDispatch strategyDispatch;
@Resource
private IStrategyRepository strategyRepository;
@Override
public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue) {
log.info("规则过滤-库存扣减 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
// 扣减库存
Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId);
// true;库存扣减成功,TAKE_OVER 规则节点接管,返回奖品ID,奖品规则配置
if (status) {
log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
// 写入延迟队列,延迟消费更新数据库记录。【在trigger的job;UpdateAwardStockJob 下消费队列,更新数据库记录】
strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
.strategyId(strategyId)
.awardId(awardId)
.build());
return DefaultTreeFactory.TreeActionEntity.builder()
.ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
.strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
.awardId(awardId)
.awardRuleValue(ruleValue)
.build())
.build();
}
// 如果库存不足,则直接返回放行
log.warn("规则过滤-库存扣减-告警,库存不足。userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
return DefaultTreeFactory.TreeActionEntity.builder()
.ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
.build();
}
}
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/strategy/service/rule/tree/impl/RuleStockLogicTreeNode.java
|
Java
|
unknown
| 2,635
|
/**
* 外部接口适配器层;当需要调用外部接口时,则创建出这一层,并定义接口,之后由基础设施层的 adapter 层具体实现
*/
package org.example.domain.xxx.adapter;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/xxx/adapter/package-info.java
|
Java
|
unknown
| 204
|
/**
* 聚合对象;
* 1. 聚合实体和值对象
* 2. 聚合是聚合的对象,和提供基础处理对象的方法。但不建议在聚合中引入仓储和接口来做过大的逻辑。而这些复杂的操作应该放到service中处理
* 3. 对象名称 XxxAggregate
*/
package org.example.domain.xxx.model.aggregate;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/xxx/model/aggregate/package-info.java
|
Java
|
unknown
| 331
|
/**
* 实体对象;
* 1. 一般和数据库持久化对象1v1的关系,但因各自开发系统的不同,也有1vn的可能。
* 2. 如果是老系统改造,那么旧的库表冗余了太多的字段,可能会有nv1的情况
* 3. 对象名称 XxxEntity
*/
package org.example.domain.xxx.model.entity;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/xxx/model/entity/package-info.java
|
Java
|
unknown
| 315
|
/**
* 值对象;
* 1. 用于描述对象属性的值,如一个库表中有json后者一个字段多个属性信息的枚举对象
* 2. 对象名称如;XxxVO
*/
package org.example.domain.xxx.model.valobj;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/xxx/model/valobj/package-info.java
|
Java
|
unknown
| 214
|
/**
* 仓储服务
* 1. 定义仓储接口,之后由基础设施层做具体实现
*/
package org.example.domain.xxx.repository;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/xxx/repository/package-info.java
|
Java
|
unknown
| 133
|
package org.example.domain.xxx.service;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/xxx/service/package-info.java
|
Java
|
unknown
| 39
|
/**
* 聚合对象;
* 1. 聚合实体和值对象
* 2. 聚合是聚合的对象,和提供基础处理对象的方法。但不建议在聚合中引入仓储和接口来做过大的逻辑。而这些复杂的操作应该放到service中处理
* 3. 对象名称 XxxAggregate
*/
package org.example.domain.yyy.model.aggregate;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/yyy/model/aggregate/package-info.java
|
Java
|
unknown
| 331
|
/**
* 实体对象;
* 1. 一般和数据库持久化对象1v1的关系,但因各自开发系统的不同,也有1vn的可能。
* 2. 如果是老系统改造,那么旧的库表冗余了太多的字段,可能会有nv1的情况
* 3. 对象名称 XxxEntity
*/
package org.example.domain.yyy.model.entity;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/yyy/model/entity/package-info.java
|
Java
|
unknown
| 315
|
/**
* 值对象;
* 1. 用于描述对象属性的值,如一个库表中有json后者一个字段多个属性信息的枚举对象
* 2. 对象名称如;XxxVO
*/
package org.example.domain.yyy.model.valobj;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/yyy/model/valobj/package-info.java
|
Java
|
unknown
| 214
|
/**
* 仓储服务
* 1. 定义仓储接口,之后由基础设施层做具体实现
*/
package org.example.domain.yyy.repository;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/yyy/repository/package-info.java
|
Java
|
unknown
| 133
|
package org.example.domain.yyy.service;
|
2302_77187152/big-market
|
big-market-domain/src/main/java/org/example/domain/yyy/service/package-info.java
|
Java
|
unknown
| 39
|
package org.example.infrastructure.gateway.adapter;
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/gateway/adapter/package-info.java
|
Java
|
unknown
| 51
|
package org.example.infrastructure.gateway.api;
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/gateway/api/package-info.java
|
Java
|
unknown
| 47
|
package org.example.infrastructure.gateway.dto;
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/gateway/dto/package-info.java
|
Java
|
unknown
| 47
|
package org.example.infrastructure.persistent.dao;
import org.apache.ibatis.annotations.Mapper;
import org.example.infrastructure.persistent.po.Award;
import java.util.List;
/**
* 奖品表Dao
*/
@Mapper
public interface IAwardDao {
List<Award> queryAwardList();
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/dao/IAwardDao.java
|
Java
|
unknown
| 275
|
package org.example.infrastructure.persistent.dao;
import org.apache.ibatis.annotations.Mapper;
import org.example.infrastructure.persistent.po.RuleTree;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则树表DAO
* @create 2024-02-03 08:42
*/
@Mapper
public interface IRuleTreeDao {
RuleTree queryRuleTreeByTreeId(String treeId);
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/dao/IRuleTreeDao.java
|
Java
|
unknown
| 364
|
package org.example.infrastructure.persistent.dao;
import org.apache.ibatis.annotations.Mapper;
import org.example.infrastructure.persistent.po.RuleTreeNode;
import java.util.List;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则树节点表DAO
* @create 2024-02-03 08:43
*/
@Mapper
public interface IRuleTreeNodeDao {
List<RuleTreeNode> queryRuleTreeNodeListByTreeId(String treeId);
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/dao/IRuleTreeNodeDao.java
|
Java
|
unknown
| 421
|
package org.example.infrastructure.persistent.dao;
import org.apache.ibatis.annotations.Mapper;
import org.example.infrastructure.persistent.po.RuleTreeNodeLine;
import java.util.List;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则树节点连线表DAO
* @create 2024-02-03 08:44
*/
@Mapper
public interface IRuleTreeNodeLineDao {
List<RuleTreeNodeLine> queryRuleTreeNodeLineListByTreeId(String treeId);
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/dao/IRuleTreeNodeLineDao.java
|
Java
|
unknown
| 443
|
package org.example.infrastructure.persistent.dao;
import org.apache.ibatis.annotations.Mapper;
import org.example.infrastructure.persistent.po.Award;
import org.example.infrastructure.persistent.po.StrategyAward;
import java.util.List;
/**
* 策略奖品的明细配置 - 概率、规则 DAO
*/
@Mapper
public interface IStrategyAwardDao {
List<StrategyAward> queryStrategyAwardList ();
List<StrategyAward> queryStrategyAwardListByStrategyId(Long strategyId);
String queryStrategyAwardRuleModels(StrategyAward strategyAward);
void updateStrategyAwardStock(StrategyAward strategyAward);
StrategyAward queryStrategyAward(StrategyAward strategyAwardReq);
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/dao/IStrategyAwardDao.java
|
Java
|
unknown
| 684
|
package org.example.infrastructure.persistent.dao;
import org.apache.ibatis.annotations.Mapper;
import org.example.infrastructure.persistent.po.Award;
import org.example.infrastructure.persistent.po.Strategy;
import java.util.List;
/**
* 策略表Dao
*/
@Mapper
public interface IStrategyDao {
List<Strategy> queryStrategyList ();
Strategy queryStrategyByStrategyId(Long strategyId);
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/dao/IStrategyDao.java
|
Java
|
unknown
| 400
|
package org.example.infrastructure.persistent.dao;
import org.apache.ibatis.annotations.Mapper;
import org.example.infrastructure.persistent.po.Award;
import org.example.infrastructure.persistent.po.StrategyRule;
import java.util.List;
/**
* 策略规则Dao
*/
@Mapper
public interface IStrategyRuleDao {
List<StrategyRule> queryStrategyRuleList ();
StrategyRule queryStrategyRule(StrategyRule strategyRuleReq);
String queryStrategyRuleValue(StrategyRule strategyRule);
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/dao/IStrategyRuleDao.java
|
Java
|
unknown
| 491
|
package org.example.infrastructure.persistent.po;
import lombok.Data;
import java.util.Date;
/**
* 奖品表
*/
@Data
public class Award {
//自增ID
private Long id;
//抽奖奖品ID - 内部流转使用
private Long awardId;
//奖品对接标识 - 每一个都是一个对应的发奖策略
private String awardKey;
//奖品配置信息
private String awardConfig;
//奖品内容描述
private String awardDesc;
//创建时间
private Date createTime;
//更新时间
private Date updateTime;
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/po/Award.java
|
Java
|
unknown
| 557
|
package org.example.infrastructure.persistent.po;
import lombok.Data;
import java.util.Date;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则树
* @create 2024-02-03 10:29
*/
@Data
public class RuleTree {
/** 自增ID */
private Long id;
/** 规则树ID */
private String treeId;
/** 规则树名称 */
private String treeName;
/** 规则树描述 */
private String treeDesc;
/** 规则根节点 */
private String treeRootRuleKey;
/** 创建时间 */
private Date createTime;
/** 更新时间 */
private Date updateTime;
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/po/RuleTree.java
|
Java
|
unknown
| 609
|
package org.example.infrastructure.persistent.po;
import lombok.Data;
import java.util.Date;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则树节点
* @create 2024-02-03 10:29
*/
@Data
public class RuleTreeNode {
/** 自增ID */
private Long id;
/** 规则树ID */
private String treeId;
/** 规则Key */
private String ruleKey;
/** 规则描述 */
private String ruleDesc;
/** 规则比值 */
private String ruleValue;
/** 创建时间 */
private Date createTime;
/** 更新时间 */
private Date updateTime;
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/po/RuleTreeNode.java
|
Java
|
unknown
| 600
|
package org.example.infrastructure.persistent.po;
import lombok.Data;
import java.util.Date;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 规则树节点线[from -> to]
* @create 2024-02-03 10:29
*/
@Data
public class RuleTreeNodeLine {
/** 自增ID */
private Long id;
/** 规则树ID */
private String treeId;
/** 规则Key节点 From */
private String ruleNodeFrom;
/** 规则Key节点 To */
private String ruleNodeTo;
/** 限定类型;1:=;2:>;3:<;4:>=;5<=;6:enum[枚举范围] */
private String ruleLimitType;
/** 限定值(到下个节点) */
private String ruleLimitValue;
/** 创建时间 */
private Date createTime;
/** 更新时间 */
private Date updateTime;
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/po/RuleTreeNodeLine.java
|
Java
|
unknown
| 768
|
package org.example.infrastructure.persistent.po;
import lombok.Data;
import java.util.Date;
/**
* 抽奖策略
*/
@Data
public class Strategy {
/*自增ID*/
private Long id ;
/*抽奖策略ID*/
private Long strategyId;
/*抽奖策略描述*/
private String strategyDesc;
/*抽奖规则模型*/
private String ruleModels;
/*创建时间*/
private Date createTime;
/*更新时间*/
private Date updateTime;
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/po/Strategy.java
|
Java
|
unknown
| 461
|
package org.example.infrastructure.persistent.po;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/**
*策略奖品的明细配置 - 概率、规则
*/
@Data
public class StrategyAward {
//自增ID
private Long id;
//抽奖策略ID
private Long strategyId;
//抽奖奖品ID
private Integer awardId;
//抽奖奖品标题
private String awardTitle;
//抽奖奖品副标题
private String awardSubtitle;
//奖品库存总量
private Integer awardCount;
//奖品库存剩余
private Integer awardCountSurplus;
//奖品中奖概率
private BigDecimal awardRate;
//规则模型,rule配置的模型同步到此表,便于使用
private String ruleModels;
//排序
private Integer sort;
//创建时间
private Date createTime;
//更新时间
private Date updateTime;
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/po/StrategyAward.java
|
Java
|
unknown
| 889
|
package org.example.infrastructure.persistent.po;
import lombok.Data;
import java.util.Date;
/**
* 策略规则
*/
@Data
public class StrategyRule {
/** 自增ID */
private Long id;
/** 抽奖策略ID */
private Long strategyId;
/** 抽奖奖品ID【规则类型为策略,则不需要奖品ID】 */
private Integer awardId;
/** 抽象规则类型;1-策略规则、2-奖品规则 */
private Integer ruleType;
/** 抽奖规则类型【rule_random - 随机值计算、rule_lock - 抽奖几次后解锁、rule_luck_award - 幸运奖(兜底奖品)】 */
private String ruleModel;
/** 抽奖规则比值 */
private String ruleValue;
/** 抽奖规则描述 */
private String ruleDesc;
/** 创建时间 */
private Date createTime;
/** 更新时间 */
private Date updateTime;
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/po/StrategyRule.java
|
Java
|
unknown
| 853
|
package org.example.infrastructure.persistent.redis;
import org.redisson.api.*;
/**
* Redis 服务
*
* @author Fuzhengwei bugstack.cn @小傅哥
*/
public interface IRedisService {
/**
* 设置指定 key 的值
*
* @param key 键
* @param value 值
*/
<T> void setValue(String key, T value);
/**
* 设置指定 key 的值
*
* @param key 键
* @param value 值
* @param expired 过期时间
*/
<T> void setValue(String key, T value, long expired);
/**
* 获取指定 key 的值
*
* @param key 键
* @return 值
*/
<T> T getValue(String key);
/**
* 获取队列
*
* @param key 键
* @param <T> 泛型
* @return 队列
*/
<T> RQueue<T> getQueue(String key);
/**
* 加锁队列
*
* @param key 键
* @param <T> 泛型
* @return 队列
*/
<T> RBlockingQueue<T> getBlockingQueue(String key);
/**
* 延迟队列
*
* @param rBlockingQueue 加锁队列
* @param <T> 泛型
* @return 队列
*/
<T> RDelayedQueue<T> getDelayedQueue(RBlockingQueue<T> rBlockingQueue);
/**
* 自增 Key 的值;1、2、3、4
*
* @param key 键
* @return 自增后的值
*/
long incr(String key);
/**
* 指定值,自增 Key 的值;1、2、3、4
*
* @param key 键
* @return 自增后的值
*/
long incrBy(String key, long delta);
/**
* 自减 Key 的值;1、2、3、4
*
* @param key 键
* @return 自增后的值
*/
long decr(String key);
/**
* 指定值,自增 Key 的值;1、2、3、4
*
* @param key 键
* @return 自增后的值
*/
long decrBy(String key, long delta);
/**
* 移除指定 key 的值
*
* @param key 键
*/
void remove(String key);
/**
* 判断指定 key 的值是否存在
*
* @param key 键
* @return true/false
*/
boolean isExists(String key);
/**
* 将指定的值添加到集合中
*
* @param key 键
* @param value 值
*/
void addToSet(String key, String value);
/**
* 判断指定的值是否是集合的成员
*
* @param key 键
* @param value 值
* @return 如果是集合的成员返回 true,否则返回 false
*/
boolean isSetMember(String key, String value);
/**
* 将指定的值添加到列表中
*
* @param key 键
* @param value 值
*/
void addToList(String key, String value);
/**
* 获取列表中指定索引的值
*
* @param key 键
* @param index 索引
* @return 值
*/
String getFromList(String key, int index);
/**
* 获取Map
*
* @param key 键
* @return 值
*/
<K, V> RMap<K, V> getMap(String key);
/**
* 将指定的键值对添加到哈希表中
*
* @param key 键
* @param field 字段
* @param value 值
*/
void addToMap(String key, String field, String value);
/**
* 获取哈希表中指定字段的值
*
* @param key 键
* @param field 字段
* @return 值
*/
String getFromMap(String key, String field);
/**
* 获取哈希表中指定字段的值
*
* @param key 键
* @param field 字段
* @return 值
*/
<K, V> V getFromMap(String key, K field);
/**
* 将指定的值添加到有序集合中
*
* @param key 键
* @param value 值
*/
void addToSortedSet(String key, String value);
/**
* 获取 Redis 锁(可重入锁)
*
* @param key 键
* @return Lock
*/
RLock getLock(String key);
/**
* 获取 Redis 锁(公平锁)
*
* @param key 键
* @return Lock
*/
RLock getFairLock(String key);
/**
* 获取 Redis 锁(读写锁)
*
* @param key 键
* @return RReadWriteLock
*/
RReadWriteLock getReadWriteLock(String key);
/**
* 获取 Redis 信号量
*
* @param key 键
* @return RSemaphore
*/
RSemaphore getSemaphore(String key);
/**
* 获取 Redis 过期信号量
* <p>
* 基于Redis的Redisson的分布式信号量(Semaphore)Java对象RSemaphore采用了与java.util.concurrent.Semaphore相似的接口和用法。
* 同时还提供了异步(Async)、反射式(Reactive)和RxJava2标准的接口。
*
* @param key 键
* @return RPermitExpirableSemaphore
*/
RPermitExpirableSemaphore getPermitExpirableSemaphore(String key);
/**
* 闭锁
*
* @param key 键
* @return RCountDownLatch
*/
RCountDownLatch getCountDownLatch(String key);
/**
* 布隆过滤器
*
* @param key 键
* @param <T> 存放对象
* @return 返回结果
*/
<T> RBloomFilter<T> getBloomFilter(String key);
/**
* 设置值
*
* @param key key 键
* @param value 值
*/
void setAtomicLong(String key, long value);
/**
* 获取值
*
* @param key key 键
*/
Long getAtomicLong(String key);
Boolean setNx(String lockKey);
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/redis/IRedisService.java
|
Java
|
unknown
| 5,358
|
package org.example.infrastructure.persistent.redis;
import org.redisson.api.*;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.Duration;
/**
* Redis 服务 - Redisson
*
* @author Fuzhengwei bugstack.cn @小傅哥
*/
@Service("redissonService")
public class RedissonService implements IRedisService {
@Resource
private RedissonClient redissonClient;
public <T> void setValue(String key, T value) {
redissonClient.<T>getBucket(key).set(value);
}
@Override
public <T> void setValue(String key, T value, long expired) {
RBucket<T> bucket = redissonClient.getBucket(key);
bucket.set(value, Duration.ofMillis(expired));
}
public <T> T getValue(String key) {
return redissonClient.<T>getBucket(key).get();
}
@Override
public <T> RQueue<T> getQueue(String key) {
return redissonClient.getQueue(key);
}
@Override
public <T> RBlockingQueue<T> getBlockingQueue(String key) {
return redissonClient.getBlockingQueue(key);
}
@Override
public <T> RDelayedQueue<T> getDelayedQueue(RBlockingQueue<T> rBlockingQueue) {
return redissonClient.getDelayedQueue(rBlockingQueue);
}
@Override
public long incr(String key) {
return redissonClient.getAtomicLong(key).incrementAndGet();
}
@Override
public long incrBy(String key, long delta) {
return redissonClient.getAtomicLong(key).addAndGet(delta);
}
@Override
public long decr(String key) {
return redissonClient.getAtomicLong(key).decrementAndGet();
}
@Override
public long decrBy(String key, long delta) {
return redissonClient.getAtomicLong(key).addAndGet(-delta);
}
@Override
public void remove(String key) {
redissonClient.getBucket(key).delete();
}
@Override
public boolean isExists(String key) {
return redissonClient.getBucket(key).isExists();
}
public void addToSet(String key, String value) {
RSet<String> set = redissonClient.getSet(key);
set.add(value);
}
public boolean isSetMember(String key, String value) {
RSet<String> set = redissonClient.getSet(key);
return set.contains(value);
}
public void addToList(String key, String value) {
RList<String> list = redissonClient.getList(key);
list.add(value);
}
public String getFromList(String key, int index) {
RList<String> list = redissonClient.getList(key);
return list.get(index);
}
@Override
public <K, V> RMap<K, V> getMap(String key) {
return redissonClient.getMap(key);
}
public void addToMap(String key, String field, String value) {
RMap<String, String> map = redissonClient.getMap(key);
map.put(field, value);
}
public String getFromMap(String key, String field) {
RMap<String, String> map = redissonClient.getMap(key);
return map.get(field);
}
@Override
public <K, V> V getFromMap(String key, K field) {
return redissonClient.<K, V>getMap(key).get(field);
}
public void addToSortedSet(String key, String value) {
RSortedSet<String> sortedSet = redissonClient.getSortedSet(key);
sortedSet.add(value);
}
@Override
public RLock getLock(String key) {
return redissonClient.getLock(key);
}
@Override
public RLock getFairLock(String key) {
return redissonClient.getFairLock(key);
}
@Override
public RReadWriteLock getReadWriteLock(String key) {
return redissonClient.getReadWriteLock(key);
}
@Override
public RSemaphore getSemaphore(String key) {
return redissonClient.getSemaphore(key);
}
@Override
public RPermitExpirableSemaphore getPermitExpirableSemaphore(String key) {
return redissonClient.getPermitExpirableSemaphore(key);
}
@Override
public RCountDownLatch getCountDownLatch(String key) {
return redissonClient.getCountDownLatch(key);
}
@Override
public <T> RBloomFilter<T> getBloomFilter(String key) {
return redissonClient.getBloomFilter(key);
}
@Override
public Long getAtomicLong(String key) {
return redissonClient.getAtomicLong(key).get();
}
@Override
public void setAtomicLong(String key, long value) {
redissonClient.getAtomicLong(key).set(value);
}
@Override
public Boolean setNx(String key) {
return redissonClient.getBucket(key).trySet("lock");
}
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/redis/RedissonService.java
|
Java
|
unknown
| 4,607
|
package org.example.infrastructure.persistent.repository;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import org.example.domain.strategy.model.entity.StrategyEntity;
import org.example.domain.strategy.model.entity.StrategyRuleEntity;
import org.example.domain.strategy.model.valobj.*;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.infrastructure.persistent.dao.*;
import org.example.infrastructure.persistent.po.*;
import org.example.infrastructure.persistent.redis.IRedisService;
import org.example.types.common.Constants;
import org.example.types.exception.AppException;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.example.types.enums.ResponseCode.UN_ASSEMBLED_STRATEGY_ARMORY;
/**
* 策略仓储实现
*/
@Slf4j
@Repository
public class StrategyRepository implements IStrategyRepository {
@Resource
private IStrategyDao iStrategyDao;
@Resource
private IStrategyRuleDao iStrategyRuleDao;
@Resource
private IStrategyAwardDao strategyAwardDao;
@Resource
private IRedisService redisService;
@Resource
private IRuleTreeDao ruleTreeDao;
@Resource
private IRuleTreeNodeDao ruleTreeNodeDao;
@Resource
private IRuleTreeNodeLineDao ruleTreeNodeLineDao;
@Override
public List<StrategyAwardEntity> queryStrategyAwardList(Long strategyId) {
String cachekey = Constants.RedisKey.STRATEGY_AWARD_LIST_KEY + strategyId;
List<StrategyAwardEntity> strategyAwardEntities = redisService.getValue(cachekey);
if (null != strategyAwardEntities && !strategyAwardEntities.isEmpty()) {
return strategyAwardEntities;
}
List<StrategyAward> strategyAwards = strategyAwardDao.queryStrategyAwardListByStrategyId(strategyId);
strategyAwardEntities = new ArrayList<>(strategyAwards.size());
for (StrategyAward strategyAward : strategyAwards) {
StrategyAwardEntity strategyAwardEntity = StrategyAwardEntity.builder()
.strategyId(strategyAward.getStrategyId())
.awardId(strategyAward.getAwardId())
.awardTitle(strategyAward.getAwardTitle())
.awardSubtitle(strategyAward.getAwardTitle())
.awardCount(strategyAward.getAwardCount())
.awardCountSurplus(strategyAward.getAwardCountSurplus())
.awardRate(strategyAward.getAwardRate())
.sort(strategyAward.getSort())
.build();
strategyAwardEntities.add(strategyAwardEntity);
}
redisService.setValue(cachekey, strategyAwardEntities);
return strategyAwardEntities;
}
@Override
public void storeStrategyAwardSearchRateTable(String key, Integer rateRange, Map<Integer, Integer> strategyAwardSearchRateTable) {
// 1. 存储抽奖策略范围值,如10000,用于生成1000以内的随机数
redisService.setValue(Constants.RedisKey.STRATEGY_RATE_RANGE_KEY + key, rateRange);
// 2. 存储概率查找表
Map<Integer, Integer> cacheRateTable = redisService.getMap(Constants.RedisKey.STRATEGY_RATE_TABLE_KEY + key);
cacheRateTable.putAll(strategyAwardSearchRateTable);
}
@Override
public int getRateRange(Long strategyId) {
return getRateRange(String.valueOf(strategyId));
}
@Override
public int getRateRange(String key) {
String cacheKey = Constants.RedisKey.STRATEGY_RATE_RANGE_KEY + key;
if (!redisService.isExists(cacheKey)) {
throw new AppException(UN_ASSEMBLED_STRATEGY_ARMORY.getCode(), cacheKey + Constants.COLON + UN_ASSEMBLED_STRATEGY_ARMORY.getInfo());
}
return redisService.getValue(cacheKey);
}
@Override
public Integer getStrategyAwardAssemble(String key, Integer rateKey) {
return redisService.getFromMap(Constants.RedisKey.STRATEGY_RATE_TABLE_KEY + key, rateKey);
}
@Override
public StrategyEntity queryStrategyEntityByStrategyId(Long strategyId) {
// 优先从缓存获取
String cacheKey = Constants.RedisKey.STRATEGY_KEY + strategyId;
StrategyEntity strategyEntity = redisService.getValue(cacheKey);
if (null != strategyEntity) return strategyEntity;
Strategy strategy = iStrategyDao.queryStrategyByStrategyId(strategyId);
strategyEntity = StrategyEntity.builder()
.strategyId(strategy.getStrategyId())
.strategyDesc(strategy.getStrategyDesc())
.ruleModels(strategy.getRuleModels())
.build();
redisService.setValue(cacheKey, strategyEntity);
return strategyEntity;
}
@Override
public StrategyRuleEntity queryStrategyRule(Long strategyId, String ruleModel) {
StrategyRule strategyRuleReq = new StrategyRule();
strategyRuleReq.setStrategyId(strategyId);
strategyRuleReq.setRuleModel(ruleModel);
StrategyRule strategyRuleRes = iStrategyRuleDao.queryStrategyRule(strategyRuleReq);
return StrategyRuleEntity.builder()
.strategyId(strategyRuleRes.getStrategyId())
.awardId(strategyRuleRes.getAwardId())
.ruleType(strategyRuleRes.getRuleType())
.ruleModel(strategyRuleRes.getRuleModel())
.ruleValue(strategyRuleRes.getRuleValue())
.ruleDesc(strategyRuleRes.getRuleDesc())
.build();
}
@Override
public String queryStrategyRuleValue(Long strategyId, Integer awardId, String ruleModel) {
StrategyRule strategyRule = new StrategyRule();
strategyRule.setStrategyId(strategyId);
strategyRule.setAwardId(awardId);
strategyRule.setRuleModel(ruleModel);
return iStrategyRuleDao.queryStrategyRuleValue(strategyRule);
}
public String queryStrategyRuleValue(Long strategyId, String ruleModel) {
return queryStrategyRuleValue(strategyId, null, ruleModel);
}
@Override
public StrategyAwardRuleModelVO queryStrategyAwardRuleModelVO(Long strategyId, Integer awardId) {
StrategyAward strategyAward = new StrategyAward();
strategyAward.setStrategyId(strategyId);
strategyAward.setAwardId(awardId);
String ruleModels = strategyAwardDao.queryStrategyAwardRuleModels(strategyAward);
return StrategyAwardRuleModelVO.builder().ruleModels(ruleModels).build();
}
@Override
public RuleTreeVO queryRuleTreeVOByTreeId(String treeId) {
// 优先从缓存获取
String cacheKey = Constants.RedisKey.RULE_TREE_VO_KEY + treeId;
RuleTreeVO ruleTreeVOCache = redisService.getValue(cacheKey);
if (null != ruleTreeVOCache) return ruleTreeVOCache;
// 从数据库获取
RuleTree ruleTree = ruleTreeDao.queryRuleTreeByTreeId(treeId);
List<RuleTreeNode> ruleTreeNodes = ruleTreeNodeDao.queryRuleTreeNodeListByTreeId(treeId);
List<RuleTreeNodeLine> ruleTreeNodeLines = ruleTreeNodeLineDao.queryRuleTreeNodeLineListByTreeId(treeId);
// 1. tree node line 转换Map结构
Map<String, List<RuleTreeNodeLineVO>> ruleTreeNodeLineMap = new HashMap<>();
for (RuleTreeNodeLine ruleTreeNodeLine : ruleTreeNodeLines) {
RuleTreeNodeLineVO ruleTreeNodeLineVO = RuleTreeNodeLineVO.builder()
.treeId(ruleTreeNodeLine.getTreeId())
.ruleNodeFrom(ruleTreeNodeLine.getRuleNodeFrom())
.ruleNodeTo(ruleTreeNodeLine.getRuleNodeTo())
.ruleLimitType(RuleLimitTypeVO.valueOf(ruleTreeNodeLine.getRuleLimitType()))
.ruleLimitValue(RuleLogicCheckTypeVO.valueOf(ruleTreeNodeLine.getRuleLimitValue()))
.build();
List<RuleTreeNodeLineVO> ruleTreeNodeLineVOList = ruleTreeNodeLineMap.computeIfAbsent(ruleTreeNodeLine.getRuleNodeFrom(), k -> new ArrayList<>());
ruleTreeNodeLineVOList.add(ruleTreeNodeLineVO);
}
// 2. tree node 转换为Map结构
Map<String, RuleTreeNodeVO> treeNodeMap = new HashMap<>();
for (RuleTreeNode ruleTreeNode : ruleTreeNodes) {
RuleTreeNodeVO ruleTreeNodeVO = RuleTreeNodeVO.builder()
.treeId(ruleTreeNode.getTreeId())
.ruleKey(ruleTreeNode.getRuleKey())
.ruleDesc(ruleTreeNode.getRuleDesc())
.ruleValue(ruleTreeNode.getRuleValue())
.treeNodeLineVOList(ruleTreeNodeLineMap.get(ruleTreeNode.getRuleKey()))
.build();
treeNodeMap.put(ruleTreeNode.getRuleKey(), ruleTreeNodeVO);
}
// 3. 构建 Rule Tree
RuleTreeVO ruleTreeVODB = RuleTreeVO.builder()
.treeId(ruleTree.getTreeId())
.treeName(ruleTree.getTreeName())
.treeDesc(ruleTree.getTreeDesc())
.treeRootRuleNode(ruleTree.getTreeRootRuleKey())
.treeNodeMap(treeNodeMap)
.build();
redisService.setValue(cacheKey, ruleTreeVODB);
return ruleTreeVODB;
}
@Override
public void cacheStrategyAwardCount(String cacheKey, Integer awardCount) {
if (redisService.isExists(cacheKey)) return;
redisService.setAtomicLong(cacheKey, awardCount);
}
@Override
public Boolean subtractionAwardStock(String cacheKey) {
long surplus = redisService.decr(cacheKey);
if (surplus < 0) {
// 库存小于0,恢复为0个
redisService.setValue(cacheKey, 0);
return false;
}
// 1. 按照cacheKey decr 后的值,如 99、98、97 和 key 组成为库存锁的key进行使用。
// 2. 加锁为了兜底,如果后续有恢复库存,手动处理等,也不会超卖。因为所有的可用库存key,都被加锁了。
String lockKey = cacheKey + Constants.UNDERLINE + surplus;
Boolean lock = redisService.setNx(lockKey);
if (!lock) {
log.info("策略奖品库存加锁失败 {}", lockKey);
}
return lock;
}
@Override
public void awardStockConsumeSendQueue(StrategyAwardStockKeyVO strategyAwardStockKeyVO) {
String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_QUEUE_KEY;
//先创建队列,再把队列加入延迟队列
RBlockingQueue<StrategyAwardStockKeyVO> blockingQueue = redisService.getBlockingQueue(cacheKey);
RDelayedQueue<StrategyAwardStockKeyVO> delayedQueue = redisService.getDelayedQueue(blockingQueue);
delayedQueue.offer(strategyAwardStockKeyVO, 3, TimeUnit.SECONDS);
}
@Override
public StrategyAwardStockKeyVO takeQueueValue() {
String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_QUEUE_KEY;
RBlockingQueue<StrategyAwardStockKeyVO> destinationQueue = redisService.getBlockingQueue(cacheKey);
return destinationQueue.poll();
}
@Override
public void updateStrategyAwardStock(Long strategyId, Integer awardId) {
StrategyAward strategyAward = new StrategyAward();
strategyAward.setStrategyId(strategyId);
strategyAward.setAwardId(awardId);
strategyAwardDao.updateStrategyAwardStock(strategyAward);
}
@Override
public StrategyAwardEntity queryStrategyAwardEntity(Long strategyId, Integer awardId) {
// 优先从缓存获取
String cacheKey = Constants.RedisKey.STRATEGY_AWARD_KEY + strategyId + Constants.UNDERLINE + awardId;
StrategyAwardEntity strategyAwardEntity = redisService.getValue(cacheKey);
if (null != strategyAwardEntity) return strategyAwardEntity;
// 查询数据
StrategyAward strategyAwardReq = new StrategyAward();
strategyAwardReq.setStrategyId(strategyId);
strategyAwardReq.setAwardId(awardId);
StrategyAward strategyAwardRes = strategyAwardDao.queryStrategyAward(strategyAwardReq);
// 转换数据
strategyAwardEntity = StrategyAwardEntity.builder()
.strategyId(strategyAwardRes.getStrategyId())
.awardId(strategyAwardRes.getAwardId())
.awardTitle(strategyAwardRes.getAwardTitle())
.awardSubtitle(strategyAwardRes.getAwardSubtitle())
.awardCount(strategyAwardRes.getAwardCount())
.awardCountSurplus(strategyAwardRes.getAwardCountSurplus())
.awardRate(strategyAwardRes.getAwardRate())
.sort(strategyAwardRes.getSort())
.build();
// 缓存结果
redisService.setValue(cacheKey, strategyAwardEntity);
// 返回数据
return strategyAwardEntity;
}
}
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/repository/StrategyRepository.java
|
Java
|
unknown
| 13,106
|
/**
* 仓储实现;用于实现 domain 中定义的仓储接口,如;IXxxRepository 在 Repository 中调用服务
*/
package org.example.infrastructure.persistent.repository;
|
2302_77187152/big-market
|
big-market-infrastructure/src/main/java/org/example/infrastructure/persistent/repository/package-info.java
|
Java
|
unknown
| 182
|
package org.example.trigger.http;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.entity.RaffleAwardEntity;
import org.example.domain.strategy.model.entity.RaffleFactorEntity;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import org.example.domain.strategy.service.IRaffleAward;
import org.example.domain.strategy.service.IRaffleStrategy;
import org.example.domain.strategy.service.armory.IStrategyArmory;
import org.example.trigger.api.IRaffleService;
import org.example.trigger.api.dto.RaffleAwardListRequestDTO;
import org.example.trigger.api.dto.RaffleAwardListResponseDTO;
import org.example.trigger.api.dto.RaffleRequestDTO;
import org.example.trigger.api.dto.RaffleResponseDTO;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;
import org.example.types.model.Response;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 营销抽奖服务
* @create 2024-02-14 09:21
*/
@Slf4j
@RestController()
@CrossOrigin("${app.config.cross-origin}")
@RequestMapping("/api/${app.config.api-version}/raffle/")
public class RaffleController implements IRaffleService {
@Resource
private IRaffleAward raffleAward;
@Resource
private IRaffleStrategy raffleStrategy;
@Resource
private IStrategyArmory strategyArmory;
/**
* 策略装配,将策略信息装配到缓存中
* <a href="http://localhost:8091/api/v1/raffle/strategy_armory">/api/v1/raffle/strategy_armory</a>
*
* @param strategyId 策略ID
* @return 装配结果
*/
@RequestMapping(value = "strategy_armory", method = RequestMethod.GET)
@Override
public Response<Boolean> strategyArmory(@RequestParam Long strategyId) {
try {
log.info("抽奖策略装配开始 strategyId:{}", strategyId);
boolean armoryStatus = strategyArmory.assembleLotteryStrategy(strategyId);
Response<Boolean> response = Response.<Boolean>builder()
.code(ResponseCode.SUCCESS.getCode())
.info(ResponseCode.SUCCESS.getInfo())
.data(armoryStatus)
.build();
log.info("抽奖策略装配完成 strategyId:{} response: {}", strategyId, JSON.toJSONString(response));
return response;
} catch (Exception e) {
log.error("抽奖策略装配失败 strategyId:{}", strategyId, e);
return Response.<Boolean>builder()
.code(ResponseCode.UN_ERROR.getCode())
.info(ResponseCode.UN_ERROR.getInfo())
.build();
}
}
/**
* 查询奖品列表
* <a href="http://localhost:8091/api/v1/raffle/query_raffle_award_list">/api/v1/raffle/query_raffle_award_list</a>
* 请求参数 raw json
*
* @param requestDTO {"strategyId":1000001}
* @return 奖品列表
*/
@RequestMapping(value = "query_raffle_award_list", method = RequestMethod.POST)
@Override
public Response<List<RaffleAwardListResponseDTO>> queryRaffleAwardList(@RequestBody RaffleAwardListRequestDTO requestDTO) {
try {
log.info("查询抽奖奖品列表配开始 strategyId:{}", requestDTO.getStrategyId());
// 查询奖品配置
List<StrategyAwardEntity> strategyAwardEntities = raffleAward.queryRaffleStrategyAwardList(requestDTO.getStrategyId());
List<RaffleAwardListResponseDTO> raffleAwardListResponseDTOS = new ArrayList<>(strategyAwardEntities.size());
for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
raffleAwardListResponseDTOS.add(RaffleAwardListResponseDTO.builder()
.awardId(strategyAward.getAwardId())
.awardTitle(strategyAward.getAwardTitle())
.awardSubtitle(strategyAward.getAwardSubtitle())
.sort(strategyAward.getSort())
.build());
}
Response<List<RaffleAwardListResponseDTO>> response = Response.<List<RaffleAwardListResponseDTO>>builder()
.code(ResponseCode.SUCCESS.getCode())
.info(ResponseCode.SUCCESS.getInfo())
.data(raffleAwardListResponseDTOS)
.build();
log.info("查询抽奖奖品列表配置完成 strategyId:{} response: {}", requestDTO.getStrategyId(), JSON.toJSONString(response));
// 返回结果
return response;
} catch (Exception e) {
log.error("查询抽奖奖品列表配置失败 strategyId:{}", requestDTO.getStrategyId(), e);
return Response.<List<RaffleAwardListResponseDTO>>builder()
.code(ResponseCode.UN_ERROR.getCode())
.info(ResponseCode.UN_ERROR.getInfo())
.build();
}
}
/**
* 随机抽奖接口
* <a href="http://localhost:8091/api/v1/raffle/random_raffle">/api/v1/raffle/random_raffle</a>
*
* @param requestDTO 请求参数 {"strategyId":1000001}
* @return 抽奖结果
*/
@RequestMapping(value = "random_raffle", method = RequestMethod.POST)
@Override
public Response<RaffleResponseDTO> randomRaffle(@RequestBody RaffleRequestDTO requestDTO) {
try {
log.info("随机抽奖开始 strategyId: {}", requestDTO.getStrategyId());
// 调用抽奖接口
RaffleAwardEntity raffleAwardEntity = raffleStrategy.performRaffle(RaffleFactorEntity.builder()
.userId("system")
.strategyId(requestDTO.getStrategyId())
.build());
// 封装返回结果
Response<RaffleResponseDTO> response = Response.<RaffleResponseDTO>builder()
.code(ResponseCode.SUCCESS.getCode())
.info(ResponseCode.SUCCESS.getInfo())
.data(RaffleResponseDTO.builder()
.awardId(raffleAwardEntity.getAwardId())
.awardIndex(raffleAwardEntity.getSort())
.build())
.build();
log.info("随机抽奖完成 strategyId: {} response: {}", requestDTO.getStrategyId(), JSON.toJSONString(response));
return response;
} catch (AppException e) {
log.error("随机抽奖失败 strategyId:{} {}", requestDTO.getStrategyId(), e.getInfo());
return Response.<RaffleResponseDTO>builder()
.code(e.getCode())
.info(e.getInfo())
.build();
} catch (Exception e) {
log.error("随机抽奖失败 strategyId:{}", requestDTO.getStrategyId(), e);
return Response.<RaffleResponseDTO>builder()
.code(ResponseCode.UN_ERROR.getCode())
.info(ResponseCode.UN_ERROR.getInfo())
.build();
}
}
}
|
2302_77187152/big-market
|
big-market-trigger/src/main/java/org/example/trigger/http/RaffleController.java
|
Java
|
unknown
| 7,214
|
/**
* HTTP 接口服务
*/
package org.example.trigger.http;
|
2302_77187152/big-market
|
big-market-trigger/src/main/java/org/example/trigger/http/package-info.java
|
Java
|
unknown
| 62
|
package org.example.trigger.job;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import org.example.domain.strategy.service.IRaffleStock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author @yk
* @description :更新奖品库存任务;为了不让更新库存的压力打到数据库中,这里采用了redis更新缓存库存,异步队列更新数据库,数据库表最终一致即可。
* @create 2024-03-14 20:47
*/
@Slf4j
@Component()
public class UpdateAwardStockJob {
@Resource
private IRaffleStock raffleStock;
@Scheduled(cron = "0/5 * * * * ?")
public void exec() {
try {
log.info("定时任务,更新奖品消耗库存【延迟队列获取,降低对数据库的更新频次,不要产生竞争】");
StrategyAwardStockKeyVO strategyAwardStockKeyVO = raffleStock.takeQueueValue();
if (null == strategyAwardStockKeyVO) return;
log.info("定时任务,更新奖品消耗库存 strategyId:{} awardId:{}", strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId());
raffleStock.updateStrategyAwardStock(strategyAwardStockKeyVO.getStrategyId(), strategyAwardStockKeyVO.getAwardId());
} catch (Exception e) {
log.error("定时任务,更新奖品消耗库存失败", e);
}
}
}
|
2302_77187152/big-market
|
big-market-trigger/src/main/java/org/example/trigger/job/UpdateAwardStockJob.java
|
Java
|
unknown
| 1,504
|
/**
* 任务服务,可以选择使用 Spring 默认提供的 Schedule https://bugstack.cn/md/road-map/quartz.html
*/
package org.example.trigger.job;
|
2302_77187152/big-market
|
big-market-trigger/src/main/java/org/example/trigger/job/package-info.java
|
Java
|
unknown
| 153
|
/**
* 监听服务;在单体服务中,解耦流程。类似MQ的使用,如Spring的Event,Guava的事件总线都可以。如果使用了 Redis 那么也可以有发布/订阅使用。
* Guava:https://bugstack.cn/md/road-map/guava.html
*/
package org.example.trigger.listener;
|
2302_77187152/big-market
|
big-market-trigger/src/main/java/org/example/trigger/listener/package-info.java
|
Java
|
unknown
| 288
|
package org.example.types.common;
public class Constants {
public final static String SPLIT = ",";
public final static String COLON = ":";
public final static String SPACE = " ";
public final static String UNDERLINE = "_";
public static class RedisKey {
public static String STRATEGY_KEY = "big_market_strategy_key_";
public static String STRATEGY_AWARD_KEY = "big_market_strategy_award_key_";
public static String STRATEGY_AWARD_LIST_KEY = "big_market_strategy_award_list_key_";
public static String STRATEGY_RATE_TABLE_KEY = "big_market_strategy_rate_table_key_";
public static String STRATEGY_RATE_RANGE_KEY = "big_market_strategy_rate_range_key_";
public static String RULE_TREE_VO_KEY = "rule_tree_vo_key_";
public static String STRATEGY_AWARD_COUNT_KEY = "strategy_award_count_key_";
public static String STRATEGY_AWARD_COUNT_QUEUE_KEY = "strategy_award_count_queue_key";
}
}
|
2302_77187152/big-market
|
big-market-types/src/main/java/org/example/types/common/Constants.java
|
Java
|
unknown
| 976
|
package org.example.types.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Getter
public enum ResponseCode {
SUCCESS("0000", "成功"),
UN_ERROR("0001", "未知失败"),
ILLEGAL_PARAMETER("0002", "非法参数"),
STRATEGY_RULE_WEIGHT_IS_NULL("ERR_BIZ_001", "业务异常,策略规则中 rule_weight 权重规则已适用但未配置"),
UN_ASSEMBLED_STRATEGY_ARMORY("ERR_BIZ_002", "抽奖策略配置未装配,请通过IStrategyArmory完成装配"),
;
private String code;
private String info;
}
|
2302_77187152/big-market
|
big-market-types/src/main/java/org/example/types/enums/ResponseCode.java
|
Java
|
unknown
| 623
|
package org.example.types.exception;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class AppException extends RuntimeException {
private static final long serialVersionUID = 5317680961212299217L;
/** 异常码 */
private String code;
/** 异常信息 */
private String info;
public AppException(String code) {
this.code = code;
}
public AppException(String code, Throwable cause) {
this.code = code;
super.initCause(cause);
}
public AppException(String code, String message) {
this.code = code;
this.info = message;
}
public AppException(String code, String message, Throwable cause) {
this.code = code;
this.info = message;
super.initCause(cause);
}
@Override
public String toString() {
return "org.example.x.api.types.exception.XApiException{" +
"code='" + code + '\'' +
", info='" + info + '\'' +
'}';
}
}
|
2302_77187152/big-market
|
big-market-types/src/main/java/org/example/types/exception/AppException.java
|
Java
|
unknown
| 1,061
|
package org.example.types.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Response<T> implements Serializable {
private String code;
private String info;
private T data;
}
|
2302_77187152/big-market
|
big-market-types/src/main/java/org/example/types/model/Response.java
|
Java
|
unknown
| 354
|
CONTAINER_NAME=big-market
IMAGE_NAME=system/big-market:1.0-SNAPSHOT
PORT=8091
echo "容器部署开始 ${CONTAINER_NAME}"
# 停止容器
docker stop ${CONTAINER_NAME}
# 删除容器
docker rm ${CONTAINER_NAME}
# 启动容器
docker run --name ${CONTAINER_NAME} \
-p ${PORT}:${PORT} \
-d ${IMAGE_NAME}
echo "容器部署成功 ${CONTAINER_NAME}"
docker logs -f ${CONTAINER_NAME}
|
2302_77187152/big-market
|
docs/dev-ops/app/start.sh
|
Shell
|
unknown
| 383
|
docker stop big-market
|
2302_77187152/big-market
|
docs/dev-ops/app/stop.sh
|
Shell
|
unknown
| 22
|
package com.cxl.ext;
public class mbsj {
public static void main(String[] args) {
text ww = new text();
ww.cal();
texta a1 = new texta();
a1.cal();
}
}
abstract class tmp{
abstract void job();
public void cal(){
long star=System.currentTimeMillis();
job();
long end=System.currentTimeMillis();
System.out.println(end-star);
}
}
class text extends tmp{
@Override
void job() {
for (long i = 0; i < 1000000000; i++) {
i++;
}
}
}
class texta extends tmp{
@Override
void job() {
for (long i = 0; i < 900000000; i++) {
i++;
}
}
}
|
2302_79273957/application-of-class
|
final抽象类接口/src/com/cxl/ext/mbsj.java
|
Java
|
unknown
| 724
|
package com.cxl.ext;
public class text01 {
public static void main(String[] args) {
A a = new A(2);
// B b = new B(3);
}
}
class A extends B{
public A(int i) {
super(i);
}
@Override
public void AA() {
System.out.println("A类被调用");
}
}
abstract class C extends B{
public C(int i) {
super(i);
}
@Override
public void AA() {
System.out.println("C抽象类被调用");
}
}
abstract class B{
private int i;
public abstract void AA();
private void aa(){
System.out.println(i);
}
public B(int i) {
this.i = i;
}
}
|
2302_79273957/application-of-class
|
final抽象类接口/src/com/cxl/ext/text01.java
|
Java
|
unknown
| 699
|
package com.finaltext;
public class text01 {
public static void main(String[] args) {
CC cc = new CC();
cc.aa=9;
// cc.pp=6;
cc.gg();
}
}
final class AA{
public void pp(){
}
}
class zz{
public void pp(){
}
public final void gg(){
}
}
//class BB extends AA{}
final class CC extends zz{
final int pp=9;
int aa=0;
@Override
public void pp() {
super.pp();
}
// public void gg(){}
}
|
2302_79273957/application-of-class
|
final抽象类接口/src/com/finaltext/text01.java
|
Java
|
unknown
| 509
|
package com.jiekou;
import javax.xml.transform.Source;
public class cammer implements usb {
@Override
public void start() {
System.out.println("相机开始工作");
}
@Override
public void stop() {
System.out.println("相机停止工作");
}
}
|
2302_79273957/application-of-class
|
final抽象类接口/src/com/jiekou/cammer.java
|
Java
|
unknown
| 305
|
package com.jiekou;
public class comp {
public void work(usb e){
e.start();
e.stop();
}
}
|
2302_79273957/application-of-class
|
final抽象类接口/src/com/jiekou/comp.java
|
Java
|
unknown
| 123
|
package com.jiekou;
import java.util.function.DoubleToIntFunction;
public class phone implements usb {
public void sj(){
System.out.println("手机以死机");
}
@Override
public void start() {
System.out.println("phone开始工作");
}
@Override
public void stop() {
System.out.println("phone停止工作");
}
}
|
2302_79273957/application-of-class
|
final抽象类接口/src/com/jiekou/phone.java
|
Java
|
unknown
| 390
|
package com.jiekou;
public class text {
public static void main(String[] args) {
phone xm = new phone();
comp q1 = new comp();
q1.work(xm);
usb u=new phone();
u=new cammer();
usb arr[]=new usb[4];
arr[1]=new phone();
arr[1].stop();
if(arr[1] instanceof phone){
phone app=(phone)arr[1];
app.sj();
}
}
}
interface id{
}
interface it extends id,usb{
//接口可以继承接口
}
class aaa implements id ,it {
@Override
public void ok() {
}
@Override
public void start() {
}
@Override
public void stop() {
}//继承和接口可以写在一起
}
|
2302_79273957/application-of-class
|
final抽象类接口/src/com/jiekou/text.java
|
Java
|
unknown
| 742
|
package com.jiekou;
public interface usb {
public int n1=10;
default public void ok(){
System.out.println(" ");//可以是静态和默认方法
}
public static void pp(){
System.out.println(" ");
}
public void start();
public void stop();
}
|
2302_79273957/application-of-class
|
final抽象类接口/src/com/jiekou/usb.java
|
Java
|
unknown
| 302
|
package com.jiekou;
public abstract class xuliji implements usb{
//可以不用一一实现接口
}
|
2302_79273957/application-of-class
|
final抽象类接口/src/com/jiekou/xuliji.java
|
Java
|
unknown
| 110
|
package chenyuannbl;
public class text04 {
public static void main(String[] args) {
AA aa= new AA();
aa.get().ii();
AA.BB bb=aa.new BB();//调用方法2
bb.ii();
}
}
class AA{
int p=100;
private int a=0;
private void pp(){
System.out.println("pp被调用");
}
class BB{
int p=10;
void ii (){
System.out.println(a);
pp();
System.out.println(AA.this.p);
}
}
public BB get(){
return new BB();//调用方法一
}
}
|
2302_79273957/application-of-class
|
内部内/src/chenyuannbl/text04.java
|
Java
|
unknown
| 584
|
package jintaibianl;
public class text05 {
public static void main(String[] args) {
NN nn = new NN();
NN.FF ff=new NN.FF();
ff.ss();
NN.FF f1=nn.m2();
f1.ss();
NN.FF f2=NN.m3();
f2.ss();
}
}
class NN{
int a=1;
static int e=2;
void aa(){
System.out.println("1111");
}
static void bb(){
System.out.println("222222");
}
static class FF{
public void ss() {
// a=2无法访问
// aa()无法访问
bb();
e=1;
}
}
public void m1(){
FF ff = new FF();
ff.ss();
}
public FF m2(){
return new FF();
}
public static FF m3(){
return new FF();
}
}
|
2302_79273957/application-of-class
|
内部内/src/jintaibianl/text05.java
|
Java
|
unknown
| 817
|
package jubuneibulei;
public class text01 {
public static void main(String[] args) {
ff qq = new ff();
qq.m1();
}
}
class ff{
{
class aaa{
void a3(){
System.out.println("aaa被调用");
}
}
aaa ll=new aaa();
ll.a3();
}
private int i=100;
private void oo(){
System.out.println("oo被调用");
}
public void m1(){
final class yy{//内部类中不可已有修饰符但final除外
int a=10;
int i=199;
public void ma(){
oo();
System.out.println(i);
System.out.println(ff.this.i);
}
}
yy a1=new yy();
a1.ma();
}
}
|
2302_79273957/application-of-class
|
内部内/src/jubuneibulei/text01.java
|
Java
|
unknown
| 808
|
package lliminngneibulei;
import javax.xml.crypto.dsig.CanonicalizationMethod;
public class text01 {
public static void main(String[] args) {
E e = new E();
e.aai();
}
}
class E{
private int a=88888;
public void aai(){
/*class E$1 implements ia{
重写cry
}代码底部情况*/
ia tiger=new ia(){
@Override
public void cry() { //接口的调用
System.out.println("老虎嗷嗷叫");
};
};//这里是重点
tiger.cry();
father rz=new father("jake"){
public void iii(){
}
public void mii(){ //类的调用
text();
System.out.println(a);
}
};
rz.text();//
//????
animal car=new animal(){
@Override
void ap() {
System.out.println("动物小车被调用");
}
};
car.ap();
}
}
interface ia{
public void cry();
}
class father{
public String name;
public father(String name) {
this.name = name;
}
void text(){
System.out.println("text被调用");
}
}
abstract class animal{
abstract void ap();
}
|
2302_79273957/application-of-class
|
内部内/src/lliminngneibulei/text01.java
|
Java
|
unknown
| 1,376
|
package lliminngneibulei;
public class text02 {
public static void main(String[] args) {
phone app = new phone();
app.alarm(new bell(){
@Override
public void ls() {
System.out.println("小猪起床了");
}
});
app.alarm(new bell() {
@Override
public void ls() {
System.out.println("上学去了");
}
});
}
}
interface bell{
void ls();
}
class phone{
public void alarm(bell a){
System.out.println(a.getClass());
a.ls();
}
}
|
2302_79273957/application-of-class
|
内部内/src/lliminngneibulei/text02.java
|
Java
|
unknown
| 634
|
package com.dt.com;
public class anm{
public String name="动物";
public int age=10;
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void gb(){
setAge(122);
}
public void slp(){
System.out.println("睡");
}
public void run(){
System.out.println("跑");
}
public void eat(){
System.out.println("吃");
}
public void show(){
System.out.println("hello world");
}
}
//class dog{
// public void eat(){
// System.out.println("狗吃");
// }
// public void mouse(){
// System.out.println("猫抓老鼠");
// }
//}
|
2302_79273957/application-of-class
|
多态学习/src/com/dt/com/anm.java
|
Java
|
unknown
| 816
|
package com.dt.com;
class cat extends anm{
public int age=111;
public void eat(){
System.out.println("猫吃鱼");
}
public void mouse(){
System.out.println("猫抓老鼠");
}
public void gb(){
setAge(12222);
}
}
|
2302_79273957/application-of-class
|
多态学习/src/com/dt/com/cat.java
|
Java
|
unknown
| 281
|
package com.dt.com;
public class dog extends anm{
}
|
2302_79273957/application-of-class
|
多态学习/src/com/dt/com/dog.java
|
Java
|
unknown
| 59
|
package com.dt.com;
public class food {
}
|
2302_79273957/application-of-class
|
多态学习/src/com/dt/com/food.java
|
Java
|
unknown
| 49
|
package com.dt.com;
public class lihai {
public static void main(String[] args) {
anm anm1 = new cat();
anm anm2=new anm();
anm1.eat();
System.out.println(anm1 instanceof anm);
System.out.println(anm1 instanceof cat);
anm1.gb();
System.out.println( anm1.age);//属性间不存在重写
cat cat1=(cat)anm1;//类型转换
String a="eiwo";
System.out.println(cat1 instanceof anm);
System.out.println(cat1 instanceof cat);
System.out.println(anm1 instanceof anm);
cat1.mouse();
Object obj = new Object();
System.out.println(obj instanceof anm);
System.out.println(anm1 instanceof Object);
}
}
|
2302_79273957/application-of-class
|
多态学习/src/com/dt/com/lihai.java
|
Java
|
unknown
| 750
|
package com.dt;
public class jingjie {
public static void main(String[] args) {
anm anm1= new cat();
anm1.cry();
}
}
|
2302_79273957/application-of-class
|
多态学习/src/com/dt/jingjie.java
|
Java
|
unknown
| 152
|
package com.dt;
public class xx {
public static void main(String[] args) {
A a = new A();
System.out.println(a.sum(10,20));
System.out.println(a.sum(1,2,3));//重载的多态
B b = new B();
b.say();//重写的多态
a.say();
}
}
class B{
public void say(){
System.out.println("B的方法被调用");
}
}
class A extends B{
public int sum(int a,int b,int c){
return a+b+c;
}
public int sum(int a,int b){
return a+b;
}
public void say(){
System.out.println("A的方法被调用");
}
}
|
2302_79273957/application-of-class
|
多态学习/src/com/dt/xx.java
|
Java
|
unknown
| 634
|
package com.dt;
public class xx2 {
public static void main(String[] args) {
anm anms = new cat();
anms.cry();
anms=new dog();
anms.cry();
}
}
class anm{
public void cry(){
System.out.println("动物在叫");
}
}
class cat extends anm{
public void cry(){
System.out.println("cat在叫");
}
}
class dog extends anm{
public void cry(){
System.out.println("dog在叫");
}
}
|
2302_79273957/application-of-class
|
多态学习/src/com/dt/xx2.java
|
Java
|
unknown
| 484
|
package com.text;
public class anm {
public String name;
public int age;
public anm(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
}
class dog extends anm{
public dog(String name, int age) {
super(name,age);
}
}
class cat extends anm{
public cat(String name, int age) {
super(name, age);
}
}
|
2302_79273957/application-of-class
|
多态学习/src/com/text/anm.java
|
Java
|
unknown
| 653
|
package com.text;
public class food {
public String shicai;
public int size;
public food(String shicai, int size) {
this.shicai = shicai;
this.size = size;
}
public int getSize() {
return size;
}
public String getShicai() {
return shicai;
}
public void setShicai(String shicai) {
this.shicai = shicai;
}
public void setSize(int size) {
this.size = size;
}
}
class dabanggu extends food{
public dabanggu(String shicai, int size) {
super(shicai, size);
}
}
class xiaoyi extends food{
public xiaoyi(String shicai, int size) {
super(shicai, size);
}
}
|
2302_79273957/application-of-class
|
多态学习/src/com/text/food.java
|
Java
|
unknown
| 713
|
package com.text;
public class master {
public String name;
public master(String name) {
this.name = name;
}
public void feed(anm anm1,food foods){
System.out.println("主人:"+name+"正在给"+anm1.getName()+"投喂"+foods.getShicai());
}
}
|
2302_79273957/application-of-class
|
多态学习/src/com/text/master.java
|
Java
|
unknown
| 295
|