大綱
1.商品中心的專業術語
2.商品中心的基本業務系統
3.商品中心整體架構設計以及運行流程
4.商品B端—商品編碼生成邏輯
5.商品B端—商品核心數據模型
6.商品B端—轉換建品請求數據為商品模型數據
7.商品B端—商品建品時商品編號補全與審核配置
8.商品B端—商品審核前的草稿數據保存邏輯
9.商品B端—不需審核的建品流程持久化邏輯
10.商品B端—審核工單分頁列表和商品草稿查詢
11.商品B端—商品審核時的敏感字段diff計算邏輯
12.商品B端—對草稿中的商品進行審核的邏輯
13.商品B端—商品屬性+買手+品類的數據維護
14.商品C端—通用緩存讀寫組件的實現邏輯
15.商品C端—接口代碼實現邏輯
10.商品B端—審核工單分頁列表和商品草稿查詢
//審批服務
@DubboService(version = "1.0.0", interfaceClass = AuditApi.class, retries = 0)
public class AuditApiImpl implements AuditApi {@Autowiredprivate AuditService auditService;@Overridepublic JsonResult<PageResult<AuditInfoDTO>> getTodoList(QueryTodoListRequest request) {try {//審核工單分頁列表PageResult<AuditInfoDTO> todoList = auditService.getTodoList(request);return JsonResult.buildSuccess(todoList);} catch (ProductBizException e) {log.error("biz error: request={}", JSON.toJSONString(request), e);return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());} catch (Exception e) {log.error("system error: request={}", JSON.toJSONString(request), e);return JsonResult.buildError(e.getMessage());}}@Overridepublic JsonResult<DraftDetailDTO> getDraftDetail(QueryDraftRequest request) {try {//商品草稿查詢DraftDetailDTO draftDetailDTO = auditService.getDraftDetail(request);return JsonResult.buildSuccess(draftDetailDTO);} catch (ProductBizException e) {log.error("biz error: request={}", JSON.toJSONString(request), e);return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());} catch (Exception e) {log.error("system error: request={}", JSON.toJSONString(request), e);return JsonResult.buildError(e.getMessage());}}...
}@Service
public class AuditServiceImpl implements AuditService {...//獲取審核的代辦列表@Overridepublic PageResult<AuditInfoDTO> getTodoList(QueryTodoListRequest queryTodoListRequest) {//獲取用戶審核角色AuditorListConfigDO auditor = productAuditRepository.getAuditorRuleByUserId(queryTodoListRequest.getUserId());//返回待辦列表return productAuditRepository.pageResult(queryTodoListRequest, auditor);}//查詢草稿詳情信息@Overridepublic DraftDetailDTO getDraftDetail(QueryDraftRequest queryDraftRequest) {//草稿詳情信息DraftDetailDTO draftDetailDTO = productAuditRepository.getDraftDetail(queryDraftRequest.getTicketId());//構建需要比較不同的字段數據buildDiffChangeField(draftDetailDTO);return draftDetailDTO;}//構建需要比較不同的字段的數據private void buildDiffChangeField(DraftDetailDTO draftDetailDTO) {//草稿主表信息DraftMainDTO draftMainDTO = draftDetailDTO.getDraftMainDTO();//修改后的商品數據FullProductData fullProductData = JSON.parseObject(draftMainDTO.getFeatures(), FullProductData.class);//商品新增時,item版本號是0,草稿表中的版本號是item表中的版本號加1//所以此時判斷草稿表中的版本號是小于等于1表示新增數據if (draftMainDTO.getVersionId() <= 1) {buildAddDiff(fullProductData, draftDetailDTO);} else {buildUpdateDiff(fullProductData, draftDetailDTO);}}...
}//商品審核 資源管理
@Repository
public class ProductAuditRepository {...//獲取用戶審核角色public AuditorListConfigDO getAuditorRuleByUserId(Integer userId) {LambdaQueryWrapper<AuditorListConfigDO> queryWrapper = Wrappers.lambdaQuery();queryWrapper.eq(AuditorListConfigDO::getAuditorId, userId);AuditorListConfigDO auditorListConfigDO = auditorListConfigMapper.selectOne(queryWrapper);//判斷是否查詢到對應的權限信息if (Objects.isNull(auditorListConfigDO)) {throw new ProductBizException(AuditExceptionCode.USER_AUDIT_RULE_NULL);}return auditorListConfigDO;}//獲取用戶可審核的詳細列表public PageResult<AuditInfoDTO> pageResult(QueryTodoListRequest queryTodoListRequest, AuditorListConfigDO auditor) {LambdaQueryWrapper<AuditInfoDO> queryWrapper = Wrappers.lambdaQuery();queryWrapper.eq(AuditInfoDO::getTicketStatus, AuditStatusEnum.UNAUDITED.getCode());Page<AuditInfoDO> page = new Page<>(queryTodoListRequest.getPageNum(), queryTodoListRequest.getPageSize());Integer auditorRole = auditor.getAuditorRole();//不是擁有所有審核權限,則增加限定條件,指定是建品審核或者是價格審核if (!Objects.equals(AuditorRoleEnum.ADMIN.getCode(), auditorRole)) {queryWrapper.eq(AuditInfoDO::getTicketType, auditorRole);}//根據角色查詢待辦列表return auditConverter.converterPageResult(auditInfoMapper.selectPage(page, queryWrapper));}//查詢草稿明細信息public DraftDetailDTO getDraftDetail(Long ticketId) {//1.查詢草稿主表信息DraftMainDTO draftMainDTO = auditConverter.convertDTO(getByTicketId(ticketId));//2.查詢草稿圖片列表信息List<DraftImgDTO> draftImgDTOS = getByDraft(draftMainDTO);//返回草稿的主體信息return new DraftDetailDTO(draftMainDTO, draftImgDTOS);}...
}
11.商品B端—商品審核時的敏感字段diff計算邏輯
審核時需要把Item和SKU的敏感字段的diff值顯示出來,方便審核員審核。
@Service
public class AuditServiceImpl implements AuditService {...//查詢草稿詳情信息@Overridepublic DraftDetailDTO getDraftDetail(QueryDraftRequest queryDraftRequest) {//草稿詳情信息DraftDetailDTO draftDetailDTO = productAuditRepository.getDraftDetail(queryDraftRequest.getTicketId());//構建需要比較不同的字段數據buildDiffChangeField(draftDetailDTO);return draftDetailDTO;}//構建需要比較不同的字段的數據private void buildDiffChangeField(DraftDetailDTO draftDetailDTO) {//草稿主表信息DraftMainDTO draftMainDTO = draftDetailDTO.getDraftMainDTO();//修改后的商品數據FullProductData fullProductData = JSON.parseObject(draftMainDTO.getFeatures(), FullProductData.class);//商品新增時,item版本號是0,草稿表中的版本號是item表中的版本號加1//所以此時判斷草稿表中的版本號是小于等于1表示新增數據if (draftMainDTO.getVersionId() <= 1) {buildAddDiff(fullProductData, draftDetailDTO);} else {buildUpdateDiff(fullProductData, draftDetailDTO);}}//填充新增的 商品差異變化信息private void buildAddDiff(FullProductData fullProductData, DraftDetailDTO draftDetailDTO) {//item信息ItemInfoDO itemInfoDO = fullProductData.getItemInfoDO();List<DiffValue> itemDiffValues = DiffFieldUtil.buildDiffField(itemInfoDO, null, itemDiffFields);//skuList diff 存放Map集合Map<String, List<DiffValue>> skuDiffFieldsMap = null;//sku信息List<SkuInfoDO> skuInfoDOList = fullProductData.getSkuInfoDOList();if (!CollectionUtils.isEmpty(skuInfoDOList)) {skuDiffFieldsMap = new HashMap<>(skuInfoDOList.size());for (SkuInfoDO skuInfoDO : skuInfoDOList) {List<DiffValue> skuDiffValues = DiffFieldUtil.buildDiffField(skuInfoDO, null, skuDiffFields);if (!CollectionUtils.isEmpty(skuDiffValues)) {skuDiffFieldsMap.put(skuInfoDO.getSkuId(), skuDiffValues);}}}//填充商品數據變更的差異信息buildDiffInfo(itemDiffValues, skuDiffFieldsMap, draftDetailDTO);}//填充商品數據變更的差異信息private void buildDiffInfo(List<DiffValue> itemDiffValues, Map<String, List<DiffValue>> skuDiffFieldsMap, DraftDetailDTO draftDetailDTO) {//item變更字段if (!CollectionUtils.isEmpty(itemDiffValues)) {draftDetailDTO.setItemDiffFields(itemDiffValues);}//sku變更字段if (!CollectionUtils.isEmpty(skuDiffFieldsMap)) {draftDetailDTO.setSkuDiffFields(skuDiffFieldsMap);}}//填充修改的 商品差異變化信息private void buildUpdateDiff(FullProductData fullProductData, DraftDetailDTO draftDetailDTO) {//item信息ItemInfoDO itemInfoDO = fullProductData.getItemInfoDO();//先查詢修改前itemInfoDO和修改前的skuInfoDOList,再比較變更值ItemInfoDO oldItemInfoDO = productInfoRepository.getItemByItemId(itemInfoDO.getItemId());List<DiffValue> itemDiffValues = DiffFieldUtil.buildDiffField(itemInfoDO, oldItemInfoDO, itemDiffFields);List<SkuInfoDO> oldSkuInfoDOList = productInfoRepository.listSkuByItemId(itemInfoDO.getItemId());List<SkuInfoDO> skuInfoDOList = fullProductData.getSkuInfoDOList();List<DiffValue> skuDiffValues;//skuList diff 存放Map集合Map<String, List<DiffValue>> skuDiffFieldsMap = new HashMap<>();//舊的商品集合轉換Map<String, SkuInfoDO> oldMap = oldSkuInfoDOList.stream().collect(Collectors.toMap(SkuInfoDO::getSkuId, e -> e));for (SkuInfoDO skuInfoDO : skuInfoDOList) {if (oldMap.containsKey(skuInfoDO.getSkuId())) {SkuInfoDO oldSkuInfoDO = oldMap.get(skuInfoDO.getSkuId());skuDiffValues = DiffFieldUtil.buildDiffField(skuInfoDO, oldSkuInfoDO, skuDiffFields);if (!CollectionUtils.isEmpty(skuDiffValues)) {skuDiffFieldsMap.put(skuInfoDO.getSkuId(), skuDiffValues);}}}//填充修改的商品信息buildDiffInfo(itemDiffValues, skuDiffFieldsMap, draftDetailDTO);}...
}public class DiffFieldUtil {public static List<DiffValue> buildDiffField(Object newObj, Object oldObj, List<String> diffFields) {//oldObj為null表示新增,如果newObj與oldObj類型不同,則不處理if (!Objects.isNull(oldObj) && !newObj.getClass().equals(oldObj.getClass())) {return null;}List<DiffValue> diffValues = new ArrayList<>();Field[] newObjFields = newObj.getClass().getDeclaredFields();Field[] oldObjFields = null;if (!Objects.isNull(oldObj)) {oldObjFields = oldObj.getClass().getDeclaredFields();}for (int i = 0; i < newObjFields.length; i++) {Field newObjField = newObjFields[i];//需要比較當前字段String fieldName = newObjField.getName();if (diffFields.contains(fieldName)) {try {Object newValue = newObjField.get(fieldName);if (Objects.isNull(oldObjFields) || !Objects.equals(oldObjFields[i].get(fieldName), newValue)) {DiffValue diffValue = new DiffValue();diffValue.setField(fieldName);diffValue.setOldValue(Objects.isNull(oldObjFields) ? null : oldObjFields[i].get(fieldName));diffValue.setNewValue(newValue);diffValues.add(diffValue);}} catch (IllegalAccessException e) {log.error("獲取字段值失敗", e);}}}return diffValues;}
}
12.商品B端—對草稿中的商品進行審核的邏輯
//審批服務
@DubboService(version = "1.0.0", interfaceClass = AuditApi.class, retries = 0)
public class AuditApiImpl implements AuditApi {@Autowiredprivate AuditService auditService;...@Overridepublic JsonResult<ExecAuditDTO> execAudit(AuditRequest request) {try {ExecAuditDTO execAuditDTO = auditService.execAudit(request);return JsonResult.buildSuccess(execAuditDTO);} catch (ProductBizException e) {log.error("biz error: request={}", JSON.toJSONString(request), e);return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());} catch (Exception e) {log.error("system error: request={}", JSON.toJSONString(request), e);return JsonResult.buildError(e.getMessage());}}
}//審核請求入參
@Data
public class AuditRequest extends BaseEntity implements Serializable {//工單idprivate Long ticketId;//審核狀態 1-通過 3-拒絕private Integer auditStatus;//拒絕原因private String rejectReason;//操作人private Integer operatorUser;
}@Service
public class AuditServiceImpl implements AuditService {...//執行審核@Transactional@Overridepublic ExecAuditDTO execAudit(AuditRequest auditRequest) {//驗證是否有可以審核,并填充審核信息AuditInfoDTO auditInfoDTO = productAuditRepository.checkAudit(auditRequest);//執行審核execGoodsAudit(auditRequest, auditInfoDTO);//處理審核的信息DB變更productAuditRepository.updateAudit(auditRequest, auditInfoDTO);return new ExecAuditDTO(Boolean.TRUE);}//商品審核private void execGoodsAudit(AuditRequest auditRequest, AuditInfoDTO auditInfoDTO) {DraftMainDTO draftMainDTO = auditInfoDTO.getDraftMainDTO();Integer ticketType = auditInfoDTO.getTicketType();//如果是審批通過,則需要更改正式表的數據if (Objects.equals(auditRequest.getAuditStatus(), AuditStatusEnum.PASS.getCode())) {FullProductData fullProductData = JSON.parseObject(draftMainDTO.getFeatures(), FullProductData.class);//建品審核if (Objects.equals(ticketType, AuditTypeEnum.GOODS.getCode())) {fullProductData.getItemInfoDO().setVersionId(draftMainDTO.getVersionId());//產品信息入庫;版本號小于等于1,表示新增,否則表示修改if (fullProductData.getItemInfoDO().getVersionId() <= 1) {productInfoRepository.saveItemInfo(fullProductData);} else {productInfoRepository.updateItemInfo(fullProductData);}} else if (Objects.equals(ticketType, AuditTypeEnum.PRICE.getCode())) {SkuInfoDO skuInfoDO = fullProductData.getSkuInfoDOList().get(0);productInfoRepository.saveRecord(skuInfoDO);}}}...
}//商品審核 資源管理
@Repository
public class ProductAuditRepository {...//驗證是否可審核,并返回審核對象public AuditInfoDTO checkAudit(AuditRequest auditRequest) {Long ticketId = auditRequest.getTicketId();//查詢審核工單AuditInfoDO auditInfoDO = auditInfoMapper.selectById(ticketId);if (Objects.isNull(auditInfoDO)) {throw new ProductBizException(AuditExceptionCode.USER_AUDIT_INFO_NULL);}AuditInfoDTO auditInfoDTO = auditConverter.convertAuditDTO(auditInfoDO);//獲取審核工單的詳情DraftMainDO draftMainDO = getByTicketId(ticketId);if (Objects.isNull(draftMainDO)) {throw new ProductBizException(AuditExceptionCode.USER_AUDIT_INFO_NULL.getErrorCode(), "審核工單詳情信息不存在");}//驗證權限是否滿足AuditorListConfigDO auditorListConfigDO = getAuditorRuleByUserId(auditRequest.getOperatorUser());if (Objects.isNull(auditorListConfigDO)) {throw new ProductBizException(AuditExceptionCode.USER_AUDIT_RULE_NULL);}//不是超級審核權限,并且擁有的審核權限與審核類型不一致if (!Objects.equals(AuditorRoleEnum.ADMIN.getCode(), auditorListConfigDO.getAuditorRole())&& !Objects.equals(draftMainDO.getTicketType(), auditorListConfigDO.getAuditorRole())) {throw new ProductBizException(ProductErrorCodeEnum.AUDIT_ERROR);}auditInfoDTO.setDraftMainDTO(auditConverter.convertDTO(draftMainDO));return auditInfoDTO;}//修改審核信息public void updateAudit(AuditRequest auditRequest, AuditInfoDTO auditInfoDTO) {DraftMainDTO draftMainDTO = auditInfoDTO.getDraftMainDTO();//軟刪除草稿表數據deleteDraftMain(draftMainDTO);//修改審核表信息updateAudit(auditInfoDTO, auditRequest);//新增審核歷史記錄saveAuditHistory(auditRequest);}//邏輯刪除草稿表數據private void deleteDraftMain(DraftMainDTO draftMainDTO) {DraftMainDO draftMainDO = auditConverter.converterDO(draftMainDTO);draftMainDO.setDelFlag(DelFlagEnum.DISABLED.getCode());//草稿表數據刪除int count = draftMainMapper.updateById(draftMainDO);if (count <= 0) {throw new ProductBizException(AuditExceptionCode.AUDIT_SQL);}}//修改審核表信息private void updateAudit(AuditInfoDTO auditInfoDTO, AuditRequest auditRequest) {AuditInfoDO auditInfoDO = auditConverter.convertAuditDO(auditInfoDTO);auditInfoDO.setTicketStatus(auditRequest.getAuditStatus());auditInfoDO.setUpdateUser(auditRequest.getOperatorUser());auditInfoDO.setUpdateTime(new Date());int count = this.auditInfoMapper.updateById(auditInfoDO);if (count <= 0) {throw new ProductBizException(AuditExceptionCode.AUDIT_SQL);}}//新增審核歷史記錄private void saveAuditHistory(AuditRequest auditRequest) {AuditHistoryDO auditHistoryDO = auditConverter.converterHistoryDO(auditRequest);auditHistoryDO.initCommon();int count = this.auditHistoryMapper.insert(auditHistoryDO);if (count <= 0) {throw new ProductBizException(AuditExceptionCode.AUDIT_SQL);}}...
}
13.商品B端—商品屬性 + 買手 + 品類的數據維護
(1)商品屬性數據維護
(2)買手數據維護
(3)品類數據維護
(1)商品屬性數據維護
//新增/編輯規格請求入參
@Data
public class AttributeRequest implements Serializable {//規格鍵信息private AttributeKeyRequest attributeKeyRequest;//規格值信息private List<AttributeValueRequest> attributeValueRequests;//操作人@NotNull(message = "操作人[operateUser]不能為空")private Integer operateUser;@Datapublic static class AttributeKeyRequest implements Serializable {//屬性key編碼private String keyCode;//屬性key名稱private String keyName;//擴展字段private String features;//排序private Integer keySort;//刪除標記(1-有效,0-刪除)private Integer delFlag;}@Datapublic static class AttributeValueRequest implements Serializable {//屬性key編碼private String keyCode;//屬性value名稱private String valueName;//擴展字段private String features;//排序private Integer valueSort;//刪除標記(1-有效,0-刪除)private Integer delFlag;}
}//規格服務
@Service
public class AttributeServiceImpl implements AttributeService {@Resourceprivate AttributeRepository attributeRepository;//新增/編輯規格鍵值接口@Transactional(rollbackFor = Exception.class)@Overridepublic AttributeResultDTO saveAttribute(AttributeRequest attributeRequest) {//入參檢查this.checkAttributeRequestParam(attributeRequest);//保存規格信息attributeRepository.saveAttribute(attributeRequest);//返回結果return new AttributeResultDTO(Boolean.TRUE);}//入參檢查private void checkAttributeRequestParam(AttributeRequest attributeRequest) {ParamCheckUtil.checkObjectNonNull(attributeRequest);//規格鍵信息AttributeRequest.AttributeKeyRequest attributeKeyRequest = attributeRequest.getAttributeKeyRequest();ParamCheckUtil.checkObjectNonNull(attributeKeyRequest);//規格值信息List<AttributeRequest.AttributeValueRequest> attributeValueRequests = attributeRequest.getAttributeValueRequests();ParamCheckUtil.checkCollectionNonEmpty(attributeValueRequests);}...
}
(2)買手數據維護
//新增/編輯買手請求入參
@Data
public class BuyerRequest implements Serializable {private Long id;//真實姓名private String realName;//花名private String roster;//買手圖像private String imageUrl;//介紹private String description;//負責的品類IDprivate String categoryId;//刪除標記(1-有效,0-刪除)private Integer delFlag;//操作人@NotNull(message = "操作人[operateUser]不能為空")private Integer operateUser;
}//買手服務
@Service
public class BuyerServiceImpl implements BuyerService {@Resourceprivate BuyerRepository buyerRepository;@Overridepublic BuyerResultDTO saveBuyer(BuyerRequest buyerRequest) {//保存買手信息buyerRepository.saveOrUpdate(buyerRequest);//返回結果信息return new BuyerResultDTO(Boolean.TRUE);}@Overridepublic BuyerListDTO getBuyerInfo(QueryBuyerListRequest queryBuyerListRequest) {List<BuyerInfoDTO> buyerInfoDTOS = buyerRepository.listBuyerInfo(queryBuyerListRequest);//返回信息return new BuyerListDTO(buyerInfoDTOS);}@Overridepublic PageResult<BuyerInfoDTO> getBuyerInfoPage(QueryBuyerPageRequest queryBuyerPageRequest) {return buyerRepository.pageResult(queryBuyerPageRequest);}
}
(3)品類數據維護
//新增/編輯品類請求入參
@Data
public class CategoryRequest implements Serializable {//idprivate Long id;//品類名稱@NotNull(message = "品類名稱[categoryName]不能為空")private String categoryName;//父ID(一級類目父ID為0)private Integer parentId;//排序(正整數,數字越小越靠前)@NotNull(message = "排序[categorySort]不能為空")private Integer categorySort;//圖標iconprivate String icon;//目錄是否展示(1-是,0-否)private Integer showMark;//是否是末級類目@NotNull(message = "末級類目[lastFlag]不能為空")private Integer lastFlag;//渠道(1-每日生鮮、2-美團、3-餓了么、4-淘鮮達、5-招商銀行)@NotNull(message = "渠道[channel]不能為空")private Integer channel;//賣家類型(1-自營,2-POP)@NotNull(message = "賣家類型[sellerType]不能為空")private Integer sellerType;//擴展字段private String feature;//刪除標記(1-有效,0-刪除)private Integer delFlag;//操作人@NotNull(message = "操作人[operateUser]不能為空")private Integer operateUser;
}//商品品類信息
@Service
public class CategoryInfoServiceImpl implements CategoryInfoService {@Resourceprivate CategoryRepository categoryRepository;@Resourceprivate CategoryInfoConverter categoryInfoConverter;//查詢品類樹@Overridepublic List<CategoryInfoTreeDTO> selectTree(QueryCategoryRequest categoryQueryRequest) {return categoryInfoConverter.converterTreeList(categoryRepository.selectTree(categoryQueryRequest));}//查詢某個層級下的品類樹(默認不帶條件查詢父類)@Overridepublic List<CategoryInfoDTO> selectChild(QueryCategoryRequest categoryQueryRequest) {//查詢某個層級的品類樹List<CategoryInfoDO> categoryInfoList = categoryRepository.listBy(categoryQueryRequest);//返回查詢結果return categoryInfoConverter.converterList(categoryInfoList);}//保存/修改品類信息@Overridepublic CategoryResultDTO saveCategory(CategoryRequest categoryRequest) {//保存品類樹categoryRepository.saveOrUpdate(categoryRequest);//返回結果信息return new CategoryResultDTO(Boolean.TRUE);}//查詢品類信息列表@Overridepublic List<CategoryInfoDTO> selectListByLike(QueryCategoryListRequest categoryListRequest) {return categoryInfoConverter.converterList(categoryRepository.selectListByLike(categoryListRequest));}
}
14.商品C端—通用緩存讀寫組件的實現邏輯
下面以獲取前臺類目為例,去說明先讀緩存再讀DB的通用緩存讀寫組件的邏輯。
FrontCategoryCache繼承自Redis緩存抽象類AbstractRedisStringCache,這個抽象類中會有一個模版方法listRedisStringData(),該方法可以根據關鍵字來批量獲取數據,并且會調用通用緩存讀寫組件的listRedisStringDataByCache()方法。
其中,listRedisStringDataByCache()方法需要傳入兩個方法:一個是獲取Redis的key的方法,一個是從DB查詢數據的方法。
//商品前臺類目服務
@DubboService(version = "1.0.0", interfaceClass = FrontCategoryApi.class, retries = 0)
public class FrontCategoryApiImpl implements FrontCategoryApi {@Resourceprivate FrontCategoryCache frontCategoryStringSource;@Resourceprivate FrontCategoryConverter frontCategoryConverter;//基于通用緩存讀寫組件,去獲取前臺類目@Overridepublic JsonResult<List<FrontCategoryDTO>> getFrontCategory(FrontCategoryQuery frontCategoryQuery) {//入參校驗checkParams(frontCategoryQuery);List<String> frontCategoryIdList = Arrays.asList(String.valueOf(frontCategoryQuery.getFrontCategoryId()));//基于通用緩存讀寫組件,先讀緩存再讀DB來獲取前臺類目Optional<List<FrontCategoryBO>> optional = frontCategoryStringSource.listRedisStringData(frontCategoryIdList);if (!optional.isPresent()) {JsonResult.buildSuccess();}List<FrontCategoryDTO> frontCategoryDTOList = frontCategoryConverter.converterFrontCategoryList(optional.get());return JsonResult.buildSuccess(frontCategoryDTOList);}...
}//Redis(String)緩存抽象類:<DO>是數據對象、<BO>是緩存對象
public abstract class AbstractRedisStringCache<DO, BO> {@Resourceprivate RedisReadWriteManager redisReadWriteManager;...//根據關鍵字批量獲取數據public Optional<List<BO>> listRedisStringData(List<String> keyList) {if (CollectionUtils.isEmpty(keyList)) {return Optional.empty();}//下面會調用通用緩存讀寫組件RedisReadWriteManager的listRedisStringDataByCache()方法//getBOClass()需要子類實現//getPendingRedisKey()也需要子類實現//最后的匿名函數中,也使用了多個需要子類實現的方法:getTableFieldsMap()、getStringDatabase()、convertDO2BO()Optional<List<BO>> boListOpt = redisReadWriteManager.listRedisStringDataByCache(keyList, getBOClass(), this::getRedisKey, (key) -> {Map<String, Object> tableFieldsMap = getTableFieldsMap(key);Optional<DO> doOpt;try {doOpt = getStringDatabase().getTableData(tableFieldsMap, queryType());} catch (Exception e) {log.error("根據關鍵字批量獲取數據出現異常 key={},paramMap={}", key, tableFieldsMap, e);return Optional.empty();}if (!doOpt.isPresent()) {return Optional.empty();}List<BO> boList = convertDO2BO(Arrays.asList(doOpt.get()));if (CollectionUtils.isEmpty(boList)) {return Optional.empty();}return Optional.of(boList.get(0));});return boListOpt;}//獲取Redis keyprotected String getRedisKey(String key) {return String.format(getPendingRedisKey(), key);}//獲取BO對象的Classprotected abstract Class<BO> getBOClass();//獲取待處理的Redis Keyprotected abstract String getPendingRedisKey();//關聯表字段值protected abstract Map<String, Object> getTableFieldsMap(String key);//獲取DB讀取對象protected abstract RedisStringDatabase<DO> getStringDatabase();//DO轉BOprotected abstract List<BO> convertDO2BO(Collection<DO> doList);...
}@Service("frontCategoryStringSource")
public class FrontCategoryCache extends AbstractRedisStringCache<FrontCategoryDO, FrontCategoryBO> {@Resourceprivate FrontCategoryStringDatabase frontCategoryStringDatabase;...//獲取BO對象的Class@Overrideprotected Class<FrontCategoryBO> getBOClass() {return FrontCategoryBO.class;}//獲取待處理的Redis Key@Overrideprotected String getPendingRedisKey() {return AbstractRedisKeyConstants.FRONT_CATEGORY_STRING;}@Overrideprotected RedisStringDatabase<FrontCategoryDO> getStringDatabase() {return frontCategoryStringDatabase;}//DO轉BO@Overrideprotected List<FrontCategoryBO> convertDO2BO(Collection<FrontCategoryDO> frontCategoryDOList) {if (CollectionUtils.isEmpty(frontCategoryDOList)) {return null;}List<FrontCategoryBO> result = Lists.newArrayList();for (FrontCategoryDO frontCategoryDO : frontCategoryDOList) {FrontCategoryBO frontCategoryBO = new FrontCategoryBO();BeanUtils.copyProperties(frontCategoryDO, frontCategoryBO);result.add(frontCategoryBO);}return result;}...
}@Service("frontCategoryStringDatabase")
public class FrontCategoryStringDatabase extends AbstractRedisStringDatabase<FrontCategoryDO> {...//獲取表數據@Overridepublic Optional<FrontCategoryDO> getTableData(Map<String, Object> tableFieldsMap, String queryType) {if (tableFieldsMap.containsKey(ID)) {QueryWrapper<FrontCategoryDO> queryWrapper = new QueryWrapper<>();queryWrapper.in("ID", Sets.newHashSet(Integer.valueOf(tableFieldsMap.get(ID).toString())));List<FrontCategoryDO> frontCategoryDOList = frontCategoryMapper.selectList(queryWrapper);if (!CollectionUtils.isEmpty(frontCategoryDOList)) {FrontCategoryDO doBase = frontCategoryDOList.get(0);if (Objects.equals(DelFlagEnum.EFFECTIVE.getCode(), doBase.getDelFlag())) {return Optional.of(doBase);}}return Optional.empty();}throw new UnsupportedOperationException();}...
}//通用緩存讀寫組件
@Service
public class RedisReadWriteManager {@Resourceprivate RedisCache redisCache;@Resourceprivate RedisLock redisLock;...//批量獲取緩存數據//@param keyList 關鍵字列表//@param clazz 需要將緩存JSON轉換的對象//@param getRedisKeyFunction 獲取Redis key的方法//@param getDbFuction 獲取數據源對象的方法//@return java.util.Optional<java.util.List<T>>public <T> Optional<List<T>> listRedisStringDataByCache(List<String> keyList, Class<T> clazz, Function<String, String> getRedisKeyFunction, Function<String, Optional<T>> getDbFuction) {try {List<T> list = Lists.newArrayList();List<String> pendingKeyList = keyList.stream().distinct().collect(toList());List<String> redisKeyList = pendingKeyList.stream().map(getRedisKeyFunction).distinct().collect(toList());List<String> cacheList = redisCache.mget(redisKeyList);for (int i = 0; i < cacheList.size(); i++) {String cache = cacheList.get(i);//過濾無效緩存if (EMPTY_OBJECT_STRING.equals(cache)) {continue;}if (StringUtils.isNotBlank(cache)) {T t = JSON.parseObject(cache, clazz);list.add(t);continue;}//緩存沒有則讀庫Optional<T> optional = getRedisStringDataByDb(pendingKeyList.get(i), getRedisKeyFunction, getDbFuction);if (optional.isPresent()) {list.add(optional.get());}}return CollectionUtils.isEmpty(list) ? Optional.empty() : Optional.of(list);} catch (Exception e) {log.error("批量獲取緩存數據異常 keyList={},clazz={}", keyList, clazz, e);throw e;}}//查詢數據庫表的數據并賦值到Redispublic <T> Optional<T> getRedisStringDataByDb(String key, Function<String, String> getRedisKeyFunction, Function<String, Optional<T>> getDbFuction) {if (StringUtils.isEmpty(key) || Objects.isNull(getDbFuction)) {return Optional.empty();}try {//使用分布式鎖if (!redisLock.lock(key)) {return Optional.empty();}String redisKey = getRedisKeyFunction.apply(key);Optional<T> optional = getDbFuction.apply(key);if (!optional.isPresent()) {//把空對象暫存到RedisredisCache.setex(redisKey, EMPTY_OBJECT_STRING, RedisKeyUtils.redisKeyRandomTime(INT_EXPIRED_ONE_DAY, TimeUnit.HOURS, NUMBER_24));log.warn("發生緩存穿透 redisKey={}", redisKey);return optional;}//把表數據對象存到RedisredisCache.setex(redisKey, JSON.toJSONString(optional.get()), RedisKeyUtils.redisKeyRandomTime(INT_EXPIRED_SEVEN_DAYS));log.info("表數據對象存到redis redisKey={}, data={}", redisKey, optional.get());return optional;} finally {redisLock.unlock(key);}}...
}
15.商品C端—接口代碼實現邏輯
(1)獲取前臺類目下的商品列表
(2)獲取商品信息和詳情接口
(1)獲取前臺類目下的商品列表
FrontCategoryRelationCache和SkuCollectCache這兩個緩存類,都繼承自抽象類AbstractRedisStringCache,并使用了通用緩存讀寫組件RedisReadWriteManager。
//商品前臺類目服務
@DubboService(version = "1.0.0", interfaceClass = FrontCategoryApi.class, retries = 0)
public class FrontCategoryApiImpl implements FrontCategoryApi {@Resourceprivate FrontCategoryRelationCache frontCategoryRelationCache;@Resourceprivate SkuCollectCache skuCollectCache;@Resourceprivate FrontCategoryConverter frontCategoryConverter;...//獲取前臺類目下的商品列表@Overridepublic JsonResult<FrontCategorySkuRelationDTO> getFrontCategorySkuList(FrontCategoryQuery frontCategoryQuery) {//入參校驗checkParams(frontCategoryQuery);List<String> frontCategoryIdList = Arrays.asList(String.valueOf(frontCategoryQuery.getFrontCategoryId()));//查詢前端類目下關聯的商品sku信息Optional<List<FrontCategoryRelationBO>> optiona = frontCategoryRelationCache.listRedisStringData(frontCategoryIdList);if (!optiona.isPresent()) {JsonResult.buildSuccess();}//填充商品的sku信息List<FrontCategoryRelationBO> frontCategoryRelationBOS = optiona.get();List<String> skuIdList = frontCategoryRelationBOS.stream().map(FrontCategoryRelationBO::getParticipateId).collect(Collectors.toList());Optional<List<SkuInfoBO>> optional = skuCollectCache.listRedisStringData(skuIdList);if (!optional.isPresent()) {JsonResult.buildSuccess();}List<Object> skuList = frontCategoryConverter.converterObjectList(optional.get());return JsonResult.buildSuccess(new FrontCategorySkuRelationDTO(skuList));}...
}@Service("frontCategoryRelationCache")
public class FrontCategoryRelationCache extends AbstractRedisStringCache<FrontCategoryRelationDO, FrontCategoryRelationBO> {@Resourceprivate FrontCategoryRelationStringDatabase frontCategoryRelationStringDatabase;@Overrideprotected Class<FrontCategoryRelationBO> getBOClass() {return FrontCategoryRelationBO.class;}@Overrideprotected String getPendingRedisKey() {return AbstractRedisKeyConstants.FRONT_CATEGORY_ITEM_RELATION_SET;}@Overrideprotected RedisStringDatabase<FrontCategoryRelationDO> getStringDatabase() {return frontCategoryRelationStringDatabase;}...
}@Service("frontCategoryRelationStringDatabase")
public class FrontCategoryRelationStringDatabase extends AbstractRedisStringDatabase<FrontCategoryRelationDO> {...@Overridepublic Optional<FrontCategoryRelationDO> getTableData(Map<String, Object> tableFieldsMap, String queryType) {if (tableFieldsMap.containsKey(FRONT_CATEGORY_ID)) {List<FrontCategoryRelationDO> frontCategoryDOList = frontCategoryMapper.queryFrontCategoryList(Arrays.asList(Long.valueOf(tableFieldsMap.get(FRONT_CATEGORY_ID).toString())));if (!CollectionUtils.isEmpty(frontCategoryDOList)) {FrontCategoryRelationDO doBase = frontCategoryDOList.get(0);if (Objects.equals(DelFlagEnum.EFFECTIVE.getCode(), doBase.getDelFlag())) {return Optional.of(doBase);}}return Optional.empty();}throw new UnsupportedOperationException();}...
}//Redis(string)緩存抽象類:<DO>數據對象、<BO>緩存對象
public abstract class AbstractRedisStringCache<DO, BO> {@Resourceprivate RedisReadWriteManager redisReadWriteManager;...//根據關鍵字批量獲取數據public Optional<List<BO>> listRedisStringData(List<String> keyList) {if (CollectionUtils.isEmpty(keyList)) {return Optional.empty();}//下面會調用通用緩存讀寫組件RedisReadWriteManager的listRedisStringDataByCache()方法//getBOClass()需要子類實現//getPendingRedisKey()也需要子類實現//最后的匿名函數中,也使用了多個需要子類實現的方法:getTableFieldsMap()、getStringDatabase()、convertDO2BO()Optional<List<BO>> boListOpt = redisReadWriteManager.listRedisStringDataByCache(keyList, getBOClass(), this::getRedisKey, (key) -> {Map<String, Object> tableFieldsMap = getTableFieldsMap(key);Optional<DO> doOpt;try {doOpt = getStringDatabase().getTableData(tableFieldsMap, queryType());} catch (Exception e) {log.error("根據關鍵字批量獲取數據出現異常 key={},paramMap={}", key, tableFieldsMap, e);return Optional.empty();}if (!doOpt.isPresent()) {return Optional.empty();}List<BO> boList = convertDO2BO(Arrays.asList(doOpt.get()));if (CollectionUtils.isEmpty(boList)) {return Optional.empty();}return Optional.of(boList.get(0));});return boListOpt;}//獲取Redis keyprotected String getRedisKey(String key) {return String.format(getPendingRedisKey(), key);}...
}
(2)獲取商品信息和詳情接口
ItemCollectCache和ProductDetailCache這兩個緩存類,都繼承自抽象類AbstractRedisStringCache,并使用了通用緩存讀寫組件RedisReadWriteManager。
@DubboService(version = "1.0.0", interfaceClass = ProductCollectApi.class, retries = 0)
public class ProductCollectApiImpl implements ProductCollectApi {@Resourceprivate ItemCollectCache itemCollectCache;@Resourceprivate ProductDetailCache productDetailCache;...//根據itemId或skuId獲取商品信息@Overridepublic JsonResult<Map<String, ProductCollectDTO>> getProductCollect(ProductCollectQuery productCollectQuery) {if (Objects.isNull(productCollectQuery) || CollectionUtils.isEmpty(productCollectQuery.getProductIdList())) {return JsonResult.buildError(ProductErrorCodeEnum.PARAM_ERROR.getErrorCode(), ProductErrorCodeEnum.PARAM_ERROR.getErrorMsg());}if (productCollectQuery.getProductIdList().size() > BaseConstants.LIMIT_100) {return JsonResult.buildError(ProductErrorCodeEnum.PRODUCT_LIMIT_ERROR.getErrorCode(), ProductErrorCodeEnum.PRODUCT_LIMIT_ERROR.getErrorMsg());}Set<String> productIdSet = Sets.newHashSet(productCollectQuery.getProductIdList());Set<String> itemIdSet = productIdSet.stream().filter(NumberUtils::isItem).collect(Collectors.toSet());List<ItemInfoBO> itemInfoBOList = Lists.newArrayList();if (!CollectionUtils.isEmpty(itemIdSet)) {Optional<List<ItemInfoBO>> itemOptional = itemCollectCache.listRedisStringData(Lists.newArrayList(itemIdSet));if (itemOptional.isPresent()) {itemInfoBOList = itemOptional.get();}}//獲取sku相關信息ProductBO productBO = buildSkuInfoList(productCollectQuery, itemInfoBOList);return JsonResult.buildSuccess(buildProductCollect(productBO.getItemInfoBOList(), productBO.getSkuInfoBOList(), productBO.getPriceBOList()));}//根據skuId獲取商品詳情@Overridepublic JsonResult<ProductDetailDTO> getProductDetail(ProductDetailQuery productDetailQuery) {if (Objects.isNull(productDetailQuery) || Objects.isNull(productDetailQuery.getSkuId())) {return JsonResult.buildError(ProductErrorCodeEnum.PARAM_ERROR.getErrorCode(), ProductErrorCodeEnum.PARAM_ERROR.getErrorMsg());}List<String> productIdList = Arrays.asList(productDetailQuery.getSkuId());Optional<List<ProductDetailBO>> optional = productDetailCache.listRedisStringData(productIdList);if (optional.isPresent()) {List<ProductDetailBO> productDetailBOS = optional.get();ProductDetailDTO productDetailDTO = productDetailConverter.converterDetail(productDetailBOS.get(0));return JsonResult.buildSuccess(productDetailDTO);}return JsonResult.buildSuccess();}...
}