找回密码
 立即注册
首页 业界区 业界 商品中心—3.商品可采可补可售的技术文档 ...

商品中心—3.商品可采可补可售的技术文档

史华乐 2025-6-11 20:17:33
大纲
1.可采可补可售业务的数据库建模设计
2.定时同步可采商品
3.定时同步可补商品
4.定时同步可售商品
5.商品中心架构梳理
 
1.可采可补可售业务的数据库建模设计
(1)可采可补可售
(2)可采业务表
(3)可补业务表
(4)可售业务表
(5)基础配置表
 
(1)可采可补可售
  1. 可售:配置了卖家组(售卖区)的商品,在该卖家组下的区域是可售状态
  2. 可补:可售商品,微仓是否可补,指⼤仓向微仓补货
  3. 可采:可售商品,⼤仓是否可采,指⼤仓采购
复制代码
(2)可采业务表
一.商品与卖家组关系表
二.组套商品与SKU关系表
三.商品ITEM表
四.商品SKU表
五.商品⽆需采购配置表
 
一.商品与卖家组关系表
  1. CREATE TABLE `sku_seller_relation` (
  2.     `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主健',
  3.     `item_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'itemId',
  4.     `sku_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'skuId',
  5.     `seller_group_id` varchar(50) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '卖家组ID',
  6.     `seller_type` int(10) DEFAULT '0' COMMENT '卖家类型(1-⾃营,2-POP)',
  7.     `relation_type` tinyint(3) DEFAULT '0' COMMENT '关系类型(1-可售,2-屏蔽)',
  8.     `del_flag` tinyint(1) DEFAULT '1' COMMENT '删除标记(1-有效,0-删除)',
  9.     `create_user` int(10) DEFAULT '0' COMMENT '创建⼈',
  10.     `create_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  11.     `update_user` int(10) DEFAULT '0' COMMENT '更新⼈',
  12.     `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  13.     PRIMARY KEY (`id`)
  14. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='商品与卖家组关系表';
复制代码
二.组套商品与SKU关系表
  1. CREATE TABLE `stack_sku_relation` (
  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  3.     `sku_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '售卖sku(组套商品)',
  4.     `stack_sku_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '普通商品skuId或原料商品skuId',
  5.     `stack_num` int(10) NOT NULL DEFAULT '0' COMMENT '数量',
  6.     `channel` tinyint(3) NOT NULL DEFAULT '0' COMMENT '渠道(1-每日⽣鲜、2-美团、3-饿了么、4-淘鲜达、5-招商银⾏)',
  7.     `seller_type` int(10) NOT NULL DEFAULT '0' COMMENT '卖家类型(1-⾃营,2-POP)',
  8.     `features` varchar(500) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '扩展字段',
  9.     `version_id` int(10) NOT NULL DEFAULT '0' COMMENT '版本号',
  10.     `del_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标记(1-有效,0-删除)',
  11.     `create_user` int(10) NOT NULL DEFAULT '0' COMMENT '创建⼈',
  12.     `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  13.     `update_user` int(10) NOT NULL DEFAULT '0' COMMENT '更新⼈',
  14.     `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更改时间',
  15.     PRIMARY KEY (`id`)
  16. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='组套商品与SKU关系表';
复制代码
三.商品ITEM表
  1. CREATE TABLE `item_info` (
  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  3.     `item_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '商品ID',
  4.     `item_name` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '商品名称',
  5.     `recommend` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '推荐语',
  6.     `item_type` int(10) NOT NULL DEFAULT '0' COMMENT '商品类型',
  7.     `channel` tinyint(3) NOT NULL DEFAULT '0' COMMENT '渠道(1-每日⽣鲜、2-美团、3-饿了么、4-淘鲜达、5-招商银⾏)',
  8.     `seller_type` int(10) NOT NULL DEFAULT '0' COMMENT '卖家类型(1-⾃营,2-POP)',
  9.     `producing_area_id` int(10) NOT NULL DEFAULT '0' COMMENT '产地ID',
  10.     `item_status` int(10) NOT NULL DEFAULT '0' COMMENT '商品状态',
  11.     `brand_id` int(10) NOT NULL DEFAULT '0' COMMENT '品牌ID',
  12.     `shelf_life` int(10) NOT NULL DEFAULT '0' COMMENT '保质期(⼩时)',
  13.     `store_condition_type` int(10) NOT NULL DEFAULT '0' COMMENT '存储条件',
  14.     `category_id` int(10) NOT NULL DEFAULT '0' COMMENT '末级品类ID',
  15.     `first_category_id` int(10) NOT NULL DEFAULT '0' COMMENT '⼀级品类ID',
  16.     `second_category_id` int(10) NOT NULL DEFAULT '0' COMMENT '⼆级品类ID',
  17.     `third_category_id` int(10) NOT NULL DEFAULT '0' COMMENT '三级品类ID',
  18.     `item_specs_value` varchar(2048) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '规格值([{"颜⾊":"⾦⾊", "内存":"128g"},{"颜⾊":"银⾊", "内存":"256g"}])',
  19.     `features` varchar(500) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '扩展字段',
  20.     `version_id` int(10) NOT NULL DEFAULT '0' COMMENT '版本号',
  21.     `del_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标记(1-有效,0-删除)',
  22.     `create_user` int(10) NOT NULL DEFAULT '0' COMMENT '创建⼈',
  23.     `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  24.     `update_user` int(10) NOT NULL DEFAULT '0' COMMENT '更新⼈',
  25.     `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  26.     PRIMARY KEY (`id`)
  27. ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='商品ITEM表';
复制代码
四.商品SKU表
  1. CREATE TABLE `sku_info` (
  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  3.     `sku_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'skuId',
  4.     `item_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'itemId',
  5.     `sku_name` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'sku名称',
  6.     `sku_type` int(10) NOT NULL DEFAULT '0' COMMENT 'sku类型(与item保持⼀致)',
  7.     `base_price` int(10) NOT NULL DEFAULT '0' COMMENT '商城价格(单位:分)',
  8.     `vip_price` int(10) NOT NULL DEFAULT '0' COMMENT '会员价格(单位:分)',
  9.     `sku_grade` int(10) NOT NULL DEFAULT '0' COMMENT '商品分级(ABC标签,运营归类处理)',
  10.     `channel` tinyint(3) NOT NULL DEFAULT '0' COMMENT '渠道(1-每日⽣鲜、2-美团、3-饿了么、4-淘鲜达、5-招商银⾏)',
  11.     `seller_type` int(10) NOT NULL DEFAULT '0' COMMENT '卖家类型(1-⾃营,2-POP)',
  12.     `sku_specs_value` varchar(2048) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '规格值({"颜⾊":"⾦⾊", "内存":"128g"})',
  13.     `features` varchar(500) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '扩展字段',
  14.     `version_id` int(10) NOT NULL DEFAULT '0' COMMENT '版本号',
  15.     `del_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标记(1-有效,0-删除)',
  16.     `create_user` int(10) NOT NULL DEFAULT '0' COMMENT '创建⼈',
  17.     `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  18.     `update_user` int(10) NOT NULL DEFAULT '0' COMMENT '更新⼈',
  19.     `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更改时间',
  20.     PRIMARY KEY (`id`)
  21. ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COMMENT='商品SKU表';
复制代码
五.商品⽆需采购配置表
  1. CREATE TABLE `item_procurement_config` (
  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  3.     `category_id` int(10) NOT NULL DEFAULT '0' COMMENT '品类ID',
  4.     `procurement_type` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否需要采购(1-需要,0-⽆需)',
  5.     `version_id` int(10) NOT NULL DEFAULT '0' COMMENT '版本号',
  6.     `del_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标记(1-有效,0-删除)',
  7.     `create_user` int(10) NOT NULL DEFAULT '0' COMMENT '创建⼈',
  8.     `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  9.     `update_user` int(10) NOT NULL DEFAULT '0' COMMENT '更新⼈',
  10.     `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更改时间',
  11.     PRIMARY KEY (`id`)
  12. ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COMMENT='商品⽆需采购配置表';
复制代码
(3)可补业务表
一.商品ITEM表
二.组套商品与SKU关系表
三.商品与卖家组关系表
四.商品属性扩展表
 
一.商品ITEM表
  1. CREATE TABLE `item_info` (
  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  3.     `item_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '商品ID',
  4.     `item_name` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '商品名称',
  5.     `recommend` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '推荐语',
  6.     `item_type` int(10) NOT NULL DEFAULT '0' COMMENT '商品类型',
  7.     `channel` tinyint(3) NOT NULL DEFAULT '0' COMMENT '渠道(1-每日⽣鲜、2-美团、3-饿了么、4-淘鲜达、5-招商银⾏)',
  8.     `seller_type` int(10) NOT NULL DEFAULT '0' COMMENT '卖家类型(1-⾃营,2-POP)',
  9.     `producing_area_id` int(10) NOT NULL DEFAULT '0' COMMENT '产地ID',
  10.     `item_status` int(10) NOT NULL DEFAULT '0' COMMENT '商品状态',
  11.     `brand_id` int(10) NOT NULL DEFAULT '0' COMMENT '品牌ID',
  12.     `shelf_life` int(10) NOT NULL DEFAULT '0' COMMENT '保质期(⼩时)',
  13.     `store_condition_type` int(10) NOT NULL DEFAULT '0' COMMENT '存储条件',
  14.     `category_id` int(10) NOT NULL DEFAULT '0' COMMENT '末级品类ID',
  15.     `first_category_id` int(10) NOT NULL DEFAULT '0' COMMENT '⼀级品类ID',
  16.     `second_category_id` int(10) NOT NULL DEFAULT '0' COMMENT '⼆级品类ID',
  17.     `third_category_id` int(10) NOT NULL DEFAULT '0' COMMENT '三级品类ID',
  18.     `item_specs_value` varchar(2048) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '规格值([{"颜⾊":"⾦⾊", "内存":"128g"},{"颜⾊":"银⾊", "内存":"256g"}])',
  19.     `features` varchar(500) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '扩展字段',
  20.     `version_id` int(10) NOT NULL DEFAULT '0' COMMENT '版本号',
  21.     `del_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标记(1-有效,0-删除)',
  22.     `create_user` int(10) NOT NULL DEFAULT '0' COMMENT '创建⼈',
  23.     `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  24.     `update_user` int(10) NOT NULL DEFAULT '0' COMMENT '更新⼈',
  25.     `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  26.     PRIMARY KEY (`id`)
  27. ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='商品ITEM表';
复制代码
二.组套商品与SKU关系表
  1. CREATE TABLE `stack_sku_relation` (
  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  3.     `sku_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '售卖sku(组套商品)',
  4.     `stack_sku_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '普通商品skuId或原料商品skuId',
  5.     `stack_num` int(10) NOT NULL DEFAULT '0' COMMENT '数量',
  6.     `channel` tinyint(3) NOT NULL DEFAULT '0' COMMENT '渠道(1-每日⽣鲜、2-美团、3-饿了么、4-淘鲜达、5-招商银⾏)',
  7.     `seller_type` int(10) NOT NULL DEFAULT '0' COMMENT '卖家类型(1-⾃营,2-POP)',
  8.     `features` varchar(500) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '扩展字段',
  9.     `version_id` int(10) NOT NULL DEFAULT '0' COMMENT '版本号',
  10.     `del_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标记(1-有效,0-删除)',
  11.     `create_user` int(10) NOT NULL DEFAULT '0' COMMENT '创建⼈',
  12.     `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  13.     `update_user` int(10) NOT NULL DEFAULT '0' COMMENT '更新⼈',
  14.     `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更改时间',
  15.     PRIMARY KEY (`id`)
  16. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='组套商品与SKU关系表';
复制代码
三.商品与卖家组关系表
  1. CREATE TABLE `sku_seller_relation` (
  2.     `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主健',
  3.     `item_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'itemId',
  4.     `sku_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'skuId',
  5.     `seller_group_id` varchar(50) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '卖家组ID',
  6.     `seller_type` int(10) DEFAULT '0' COMMENT '卖家类型(1-⾃营,2-POP)',
  7.     `relation_type` tinyint(3) DEFAULT '0' COMMENT '关系类型(1-可售,2-屏蔽)',
  8.     `del_flag` tinyint(1) DEFAULT '1' COMMENT '删除标记(1-有效,0-删除)',
  9.     `create_user` int(10) DEFAULT '0' COMMENT '创建⼈',
  10.     `create_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  11.     `update_user` int(10) DEFAULT '0' COMMENT '更新⼈',
  12.     `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  13.     PRIMARY KEY (`id`)
  14. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='商品与卖家组关系表';
复制代码
四.商品属性扩展表
  1. CREATE TABLE `attribute_extend` (
  2.     `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  3.     `participate_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '参与ID(ITEM_ID或SKU_ID)',
  4.     `participate_type` int(10) NOT NULL DEFAULT '0' COMMENT '参与类型(1-ITEM,2-SKU)',
  5.     `attribute_content` varchar(2048) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '属性内容',
  6.     `feature` varchar(500) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '扩展字段',
  7.     `version_id` int(10) NOT NULL DEFAULT '0' COMMENT '版本号',
  8.     `del_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标记(1-有效,0-删除)',
  9.     `create_user` int(10) NOT NULL DEFAULT '0' COMMENT '创建⼈',
  10.     `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  11.     `update_user` int(10) NOT NULL DEFAULT '0' COMMENT '更新⼈',
  12.     `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  13.     PRIMARY KEY (`ID`)
  14. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='商品属性扩展表';
复制代码
(4)可售业务表
一.商品与卖家组关系表
二.商品卖家库存关系表
 
一.商品与卖家组关系表
  1. CREATE TABLE `sku_seller_relation` (
  2.     `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主健',
  3.     `item_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'itemId',
  4.     `sku_id` varchar(40) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT 'skuId',
  5.     `seller_group_id` varchar(50) CHARACTER SET utf8mb4 DEFAULT NULL COMMENT '卖家组ID',
  6.     `seller_type` int(10) DEFAULT '0' COMMENT '卖家类型(1-⾃营,2-POP)',
  7.     `relation_type` tinyint(3) DEFAULT '0' COMMENT '关系类型(1-可售,2-屏蔽)',
  8.     `del_flag` tinyint(1) DEFAULT '1' COMMENT '删除标记(1-有效,0-删除)',
  9.     `create_user` int(10) DEFAULT '0' COMMENT '创建⼈',
  10.     `create_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
  11.     `update_user` int(10) DEFAULT '0' COMMENT '更新⼈',
  12.     `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  13.     PRIMARY KEY (`id`)
  14. ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='商品与卖家组关系表';
复制代码
二.商品卖家库存关系表
  1. CREATE TABLE `sku_stock_seller_relation` (
  2.     `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  3.     `sku_id` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '商品ID',
  4.     `seller_type` tinyint(3) NULL DEFAULT NULL COMMENT '卖家类型(1-⾃营,2-POP)',
  5.     `seller_id` bigint(20) NULL DEFAULT NULL COMMENT '卖家ID',
  6.     `stock_num` bigint(20) NULL DEFAULT NULL COMMENT '库存数量',
  7.     `stock_unit` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '库存单位',
  8.     `del_flag` tinyint(1) NULL DEFAULT NULL COMMENT '删除标记(1-有效,0-删除)',
  9.     `create_user` int(11) NULL DEFAULT NULL COMMENT '创建⼈',
  10.     `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
  11.     `update_user` int(11) NULL DEFAULT NULL COMMENT '更新⼈',
  12.     `update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
  13.     PRIMARY KEY (`id`) USING BTREE
  14. ) ENGINE = InnoDB AUTO INCREMENT = 1 DEFAULT CHARSET=utf8 COMMENT='商品卖家库存关系表';
复制代码
(5)基础配置表
leaf⾃增序列表leaf_alloc
  1. CREATE TABLE `leaf_alloc` (
  2.     `biz_tag` varchar(128) NOT NULL DEFAULT '' COMMENT '业务key',
  3.     `max_id` bigint(20) NOT NULL DEFAULT '1' COMMENT '当前已经分配了的最⼤id',
  4.     `step` int(11) NOT NULL COMMENT '初始步⻓,也是动态调整的最⼩步⻓',
  5.     `description` varchar(256) DEFAULT NULL COMMENT '业务key的描述',
  6.     `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '数据库维护的更新时间',
  7.     PRIMARY KEY (`biz_tag`)
  8. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='leaf⾃增序列表';
复制代码
 
2.定时同步可采商品
(1)定时调度任务定时同步可采商品
(2)定时同步可采商品时的卖家组数据分页查询
(3)过滤无效的卖家组与查询卖家组支持的可售商品
(4)卖家组支持的可售商品十万级数据量查询实现
(5)根据卖家组支持的可售商品查询商品信息
(6)对可售商品进行无需采购以及生命周期过滤
(7)对卖家组支持的可售商品进行过滤组套商品
(8)将过滤后的商品数据与卖家组进行关联
(9)读取缓存与刷入缓存的逻辑
(10)卖家组支持的可采商品与缓存的diff逻辑
(11)基于DB的分段发号器组件
 
(1)定时调度任务定时同步可采商品
使用场景:定时任务调度,可以按不同的卖家类型分任务进⾏执⾏同步结果。
  1. @Component
  2. public class RecoverableJobHandler {
  3.     @DubboReference(version = "1.0.0")
  4.     private RecoverableApi recoverableApi;
  5.     @XxlJob("syncRecoverableProduct")
  6.     public void syncAvailableProduct(RecoverableRequest request) {
  7.         XxlJobHelper.log("sync available product job starting...");
  8.         JsonResult result = recoverableApi.syncRecoverableProduct(request);
  9.         XxlJobHelper.log("sync available product job end, result:{}", result);
  10.     }
  11. }
  12. @DubboService(version = "1.0.0", interfaceClass = RecoverableApi.class, retries = 0)
  13. public class RecoverableApiImpl implements RecoverableApi {
  14.     @Autowired
  15.     private RecoverableService recoverableService;
  16.     //同步可采商品
  17.     @Override
  18.     public JsonResult syncRecoverableProduct(RecoverableRequest request) {
  19.         try {
  20.             return recoverableService.syncRecoverableProduct(request);
  21.         } catch (ProductBizException e) {
  22.             log.error("biz error: request={}", JSON.toJSONString(request), e);
  23.             return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
  24.         } catch (Exception e) {
  25.             log.error("system error: request={}", JSON.toJSONString(request), e);
  26.             return JsonResult.buildError(e.getMessage());
  27.         }
  28.     }
  29. }
  30. //商品可采业务实现类
  31. @Service
  32. public class RecoverableServiceImpl implements RecoverableService {
  33.     ...
  34.     //同步可采的数据入缓存
  35.     @Override
  36.     public JsonResult syncRecoverableProduct(RecoverableRequest request) {
  37.         Integer pageNo = 1;
  38.         //获取卖家类型对应的卖家组信息
  39.         List<SellerGroupResponse> sellerGroupResponses = querySellerGroupList(pageNo, request.getSellerGroupType());
  40.         while (!CollectionUtils.isEmpty(sellerGroupResponses)) {
  41.             //1.过滤卖家组的非有效状态信息数据
  42.             List<SellerGroupResponse> sellerGroupResponseList = sellerGroupFilter(sellerGroupResponses);
  43.             //2.根据卖家组获取卖家支持的可售商品列表
  44.             List<SkuSellerRelationDO> sellerRelationDOList = queryAvailableProduct(sellerGroupResponseList);
  45.             //3.查询商品信息,并过滤非自营的商品
  46.             List<ProductDetailDO> productDetailDOList = queryProductDetailList(sellerRelationDOList);
  47.             //4.进行item级别的商品过滤(无需采购和生命周期)
  48.             List<ProductDetailDO> itemFilterList = itemFilter(productDetailDOList);
  49.             //5.进行组套商品的商品过滤(无需采购和生命周期)
  50.             List<ProductDetailDO> suitFilterList = suitFilter(itemFilterList);
  51.             //6.将详情的商品sku信息绑定到卖家上
  52.             List<ProductSellerRelationBO> productSellerRelationBOList = buildBinding(sellerRelationDOList, suitFilterList);
  53.             //7.读取历史的缓存信息,对已经存在的缓存进行diff处理并刷入缓存
  54.             diffRecoverableCache(productSellerRelationBOList, sellerGroupResponses);
  55.             pageNo++;
  56.             sellerGroupResponses = querySellerGroupList(pageNo, request.getSellerGroupType());
  57.         }
  58.         return JsonResult.buildSuccess();
  59.     }
  60.     ...
  61. }
复制代码
具体实现:
  1. 一.调⽤查询卖家信息接⼝,传⼊卖家类型,返回对应的卖家组信息列表
  2. 二.过滤掉返回的卖家组列表中⾮有效状态的卖家组
  3. 三.根据卖家组ID列表获取这些卖家组所⽀持售卖的商品
  4. 四.根据商品sku表sku_info查询得到⾃营类型的商品
  5. 五.根据商品⽆需采购配置表获取得到不需要采购的品类信息
  6. 六.根据sku列表批量查询⽣命周期的可采结果,并过滤不可采的商品信息
  7. 七.进⾏组套商品验证,先通过sku批量查询组套商品与sku关系表
  8. 获取得到每个sku下的原料以及普通商品信息
  9. 对每个商品进⾏⽆需采购以及⽣命周期的验证
  10. 当组合商品下的sku都满⾜条件则可补,否则过滤
  11. 组套商品与SKU关系表是stack_sku_relation
  12. 八.对已经存在的缓存数据和当前这次同步处理后的数据进⾏差集处理,发⽣变化的数据才需要刷⼊缓存(新增的或者⽆效的数据)
  13. 九.构建缓存模型,对可补的商品数据进⾏缓存,缓存的模型对象为:key为'前缀标识+卖家组ID',value为'可采sku+品类'
复制代码
时序图:
1.png
流程图:
2.png
(2)定时同步可采商品时的卖家组数据分页查询
  1. @Service
  2. public class RecoverableServiceImpl implements RecoverableService {
  3.     @Autowired
  4.     private SellerRemote sellerRemote;
  5.     ...
  6.     //分页查询卖家组(售卖区)信息
  7.     public List<SellerGroupResponse> querySellerGroupList(Integer pageNo, Integer sellerGroupType) {
  8.         PageResult<SellerGroupResponse> sellerGroupPage = sellerRemote.getSellerGroupList(pageNo, CompensationConstants.SELLER_PAGE_SIZE, sellerGroupType);
  9.         return sellerGroupPage.getContent();
  10.     }
  11.     //同步可采的数据入缓存
  12.     @Override
  13.     public JsonResult syncRecoverableProduct(RecoverableRequest request) {
  14.         Integer pageNo = 1;
  15.         //获取卖家类型对应的卖家组信息
  16.         List<SellerGroupResponse> sellerGroupResponses = querySellerGroupList(pageNo, request.getSellerGroupType());
  17.         while (!CollectionUtils.isEmpty(sellerGroupResponses)) {
  18.             //1.过滤卖家组的非有效状态信息数据
  19.             List<SellerGroupResponse> sellerGroupResponseList = sellerGroupFilter(sellerGroupResponses);
  20.             //2.根据卖家组获取卖家支持的可售商品列表
  21.             List<SkuSellerRelationDO> sellerRelationDOList = queryAvailableProduct(sellerGroupResponseList);
  22.             //3.查询商品信息,并过滤非自营的商品
  23.             List<ProductDetailDO> productDetailDOList = queryProductDetailList(sellerRelationDOList);
  24.             //4.进行item级别的商品过滤(无需采购和生命周期)
  25.             List<ProductDetailDO> itemFilterList = itemFilter(productDetailDOList);
  26.             //5.进行组套商品的商品过滤(无需采购和生命周期)
  27.             List<ProductDetailDO> suitFilterList = suitFilter(itemFilterList);
  28.             //6.将详情的商品sku信息绑定到卖家上
  29.             List<ProductSellerRelationBO> productSellerRelationBOList = buildBinding(sellerRelationDOList, suitFilterList);
  30.             //7.读取历史的缓存信息,对已经存在的缓存进行diff处理并刷入缓存
  31.             diffRecoverableCache(productSellerRelationBOList, sellerGroupResponses);
  32.             pageNo++;
  33.             sellerGroupResponses = querySellerGroupList(pageNo, request.getSellerGroupType());
  34.         }
  35.         return JsonResult.buildSuccess();
  36.     }
  37.     ...
  38. }
复制代码
(3)过滤无效的卖家组与查询卖家组支持的可售商品
  1. @Service
  2. public class RecoverableServiceImpl implements RecoverableService {
  3.     ...
  4.     //对卖家组状态非有效的进行过滤
  5.     private List<SellerGroupResponse> sellerGroupFilter(List<SellerGroupResponse> sellerGroupResponses) {
  6.         //过滤无效的卖家组信息
  7.         return sellerGroupResponses.stream()
  8.             .filter(sellerGroupResponse -> SellerGroupStatusEnum.EFFECTIVE_STATUS.getCode().equals(sellerGroupResponse.getSellerGroupStatus()))
  9.             .collect(Collectors.toList());
  10.     }
  11.     //返回卖家组支持的可售商品列表
  12.     private List<SkuSellerRelationDO> queryAvailableProduct(List<SellerGroupResponse> sellerGroupResponses) {
  13.         if (!CollectionUtils.isEmpty(sellerGroupResponses)) {
  14.             //转换为所有的卖家组ID
  15.             List<Long> sellerGroupIds = sellerGroupResponses.stream().map(SellerGroupResponse::getSellerGroupId).collect(Collectors.toList());
  16.             //分页批量查询卖家组支持的可售商品列表
  17.             return productRelationRepository.pageQueryAvailableProduct(sellerGroupIds);
  18.         }
  19.         return new ArrayList<>();
  20.     }
  21.     ...
  22. }
复制代码
(4)卖家组支持的可售商品十万级数据量查询实现
一个SkuSellerRelationDO对象大概就50Byte,10万个SkuSellerRelationDO对象大概就是500万Byte=4MB。
  1. @Repository
  2. public class ProductRelationRepository {
  3.     ...
  4.     //分页查询 卖家组ID 可售商品信息
  5.     public List<SkuSellerRelationDO> pageQueryAvailableProduct(List<Long> sellerGroupIds) {
  6.         //默认集合初始大小为50000,避免扩容次数频繁,一般商品的数量最多也就是几万-几十万
  7.         List<SkuSellerRelationDO> sellerRelationAllList = new ArrayList<>(RecoverableConstants.SKU_INIT_NUM);
  8.         //一次最大查询10 卖家组ID,多个分页查询,这里做数据切割
  9.         List<List<Long>> splitList = DataCuttingUtil.dataCuttingString(sellerGroupIds, RecoverableConstants.SELLER_ID_LIMIT_NUM);
  10.         for (List<Long> sellerGroupIdList : splitList) {
  11.             List<SkuSellerRelationDO> productDetailDOList = queryAvailableProduct(sellerGroupIdList);
  12.             if (!CollectionUtils.isEmpty(productDetailDOList)) {
  13.                 sellerRelationAllList.addAll(productDetailDOList);
  14.             }
  15.         }
  16.         return sellerRelationAllList;
  17.     }
  18.     //根据卖家组ID 批量查询 可售商品信息
  19.     public List<SkuSellerRelationDO> queryAvailableProduct(List<Long> sellerGroupIds) {
  20.         //获取卖家组对应的可售商品
  21.         LambdaQueryWrapper<SkuSellerRelationDO> queryWrapper = Wrappers.lambdaQuery();
  22.         queryWrapper.in(SkuSellerRelationDO::getSellerGroupId, sellerGroupIds)
  23.             .eq(SkuSellerRelationDO::getRelationType, SkuSellerRelationTypeEnum.RELATION_TYPE_YES.getCode())
  24.             .eq(SkuSellerRelationDO::getDelFlag, DelFlagEnum.EFFECTIVE.getCode());
  25.         return skuSellerRelationMapper.selectList(queryWrapper);
  26.     }
  27.     ...
  28. }
  29. public class DataCuttingUtil {
  30.     //对集合数据进行切割,切割的数量按传入切割大小计算
  31.     public static <T> List<List<T>> dataCuttingString(List<T> splitList, Integer splitSize) {
  32.         Integer size = splitList.size();
  33.         //计算出可以切分出多少个集合对象
  34.         int limit = (size + splitSize - 1) / splitSize;
  35.         return Stream.iterate(0, n -> n + 1)
  36.             .limit(limit)
  37.             .parallel()
  38.             .map(a -> splitList.stream().skip((long) a * splitSize)
  39.             .limit(splitSize)
  40.             .parallel()
  41.             .collect(Collectors.toList()))
  42.             .collect(Collectors.toList()
  43.         );
  44.     }
  45.     ...
  46. }
复制代码
(5)根据卖家组支持的可售商品查询商品信息
  1. @Service
  2. public class RecoverableServiceImpl implements RecoverableService {
  3.     @Autowired
  4.     private ProductRepository productRepository;
  5.     ...
  6.     //根据卖家组支持的可售商品,查询商品信息并过滤非自营的商品
  7.     private List<ProductDetailDO> queryProductDetailList(List<SkuSellerRelationDO> sellerRelationDOList) {
  8.         if (!CollectionUtils.isEmpty(sellerRelationDOList)) {
  9.             //先获取到对应的skuID列表
  10.             Set<String> skuIdList = sellerRelationDOList.stream().map(SkuSellerRelationDO::getSkuId).collect(Collectors.toSet());
  11.             //一次最大查询1000skuId,多个分页查询,这里做数据切割
  12.             List<ProductDetailDO> productDetailDOList = productRepository.pageQueryProductInfoList(skuIdList);
  13.             if (!CollectionUtils.isEmpty(productDetailDOList)) {
  14.                 List<ProductDetailDO> productDetailDOS = productDetailDOList.stream()
  15.                     .filter(productDetailDO -> productDetailDO.getSellerType().equals(SellerTypeEnum.SELF.getCode()))
  16.                     .collect(Collectors.toList());
  17.                 return productDetailDOS;
  18.             }
  19.         }
  20.         return new ArrayList<>();
  21.     }
  22.     ...
  23. }
  24. @Repository
  25. public class ProductRepository {
  26.     ...
  27.     //分页查询sku信息
  28.     public List<ProductDetailDO> pageQueryProductInfoList(Set<String> skuIdList) {
  29.         //默认集合初始大小为50000,避免扩容次数频繁,一般商品的数量最多也就是几万-几十万
  30.         List<ProductDetailDO> productDetailAllList = new ArrayList<>(RecoverableConstants.SKU_INIT_NUM);
  31.         //一次最大查询1000skuId,多个分页查询,这里做数据切割
  32.         List<Set<String>> splitList = DataCuttingUtil.dataCuttingString(skuIdList, RecoverableConstants.SKU_LIMIT_NUM);
  33.         for (Set<String> skuIds : splitList) {
  34.             List<ProductDetailDO> productDetailDOList = queryProductInfoList(skuIds);
  35.             if (!CollectionUtils.isEmpty(productDetailDOList)) {
  36.                 productDetailAllList.addAll(productDetailDOList);
  37.             }
  38.         }
  39.         return productDetailAllList;
  40.     }
  41.     //批量查询商品的详情信息
  42.     public List<ProductDetailDO> queryProductInfoList(Set<String> skuId) {
  43.         return skuInfoMapper.queryProductInfoList(skuId);
  44.     }
  45.     ...
  46. }
  47. public class DataCuttingUtil {
  48.     //对集合数据进行切割,切割的数量按传入切割大小计算
  49.     public static <T> List<List<T>> dataCuttingString(List<T> splitList, Integer splitSize) {
  50.         Integer size = splitList.size();
  51.         //计算出可以切分出多少个集合对象
  52.         int limit = (size + splitSize - 1) / splitSize;
  53.         return Stream.iterate(0, n -> n + 1)
  54.             .limit(limit)
  55.             .parallel()
  56.             .map(a -> splitList.stream().skip((long) a * splitSize)
  57.             .limit(splitSize)
  58.             .parallel()
  59.             .collect(Collectors.toList()))
  60.             .collect(Collectors.toList()
  61.         );
  62.     }
  63.     ...
  64. }
复制代码
(6)对可售商品进行无需采购以及生命周期过滤
  1. @Service
  2. public class RecoverableServiceImpl implements RecoverableService {
  3.     ...
  4.     //进行item级别的商品过滤(无需采购和生命周期)
  5.     private List<ProductDetailDO> itemFilter(List<ProductDetailDO> productDetailDOList) {
  6.         if (!CollectionUtils.isEmpty(productDetailDOList)) {
  7.             //过滤掉无需采购的商品列表
  8.             List<ProductDetailDO> productDetailList = filterPurchaseProduct(productDetailDOList);
  9.             //商品进行生命周期的查询检查,过滤不符合条件的商品
  10.             return filterLifeCycle(productDetailList);
  11.         }
  12.         return productDetailDOList;
  13.     }
  14.     //过滤无需采购的item列表信息
  15.     private List<ProductDetailDO> filterPurchaseProduct(List<ProductDetailDO> suitItemDOList) {
  16.         //获取配置的无需采购的列表
  17.         List<ItemProcurementConfigDO> itemProcurementConfigList = productConfigRepository.queryProcurementConfigList();
  18.         //空集合判断
  19.         if (CollectionUtils.isEmpty(suitItemDOList)) {
  20.             return new ArrayList();
  21.         }
  22.         if (CollectionUtils.isEmpty(itemProcurementConfigList)) {
  23.             return suitItemDOList;
  24.         }
  25.         //集合转map,方便验证是否命中
  26.         Map<Integer, ItemProcurementConfigDO> procurementConfigMap = itemProcurementConfigList.stream()
  27.             .collect(Collectors.toMap(ItemProcurementConfigDO::getCategoryId, Function.identity()));
  28.         //开始过滤无需采购的商品信息
  29.         List<ProductDetailDO> productDetailDOList = suitItemDOList.stream()
  30.             .filter(productDetail -> !procurementConfigMap.containsKey(productDetail.getCategoryId()))
  31.             .collect(Collectors.toList());
  32.         //返回过滤后的商品信息
  33.         return productDetailDOList;
  34.     }
  35.     //进行商品生命周期的过滤
  36.     private List<ProductDetailDO> filterLifeCycle(List<ProductDetailDO> productDetailList) {
  37.         if (!CollectionUtils.isEmpty(productDetailList)) {
  38.             //构建调用生命周期的接口入参模型
  39.             Set<String> itemIdList = productDetailList.stream().map(ProductDetailDO::getItemId).collect(Collectors.toSet());
  40.             List<ItemExpriResultDTO> skuExpriResultDTOS = itemPeriodStageRemote.queryByItemIds(itemIdList);
  41.             //集合转map,方便验证是否命中
  42.             Map<String, ItemExpriResultDTO> itemExpriResultMap = skuExpriResultDTOS.stream().collect(Collectors.toMap(ItemExpriResultDTO::getItemId, Function.identity()));
  43.             //过滤不符合条件的商品
  44.             List<ProductDetailDO> productDetailDOList = productDetailList.stream().filter(productDetail -> {
  45.                 //没有命中不保留
  46.                 if (!itemExpriResultMap.containsKey(productDetail.getItemId())) {
  47.                     return false;
  48.                 }
  49.                 ItemExpriResultDTO itemExpriResultDTO = itemExpriResultMap.get(productDetail.getItemId());
  50.                 //可采的状态返回true
  51.                 return itemExpriResultDTO.getPurchaseStatus().equals(ItemExpriEnum.RECOVERABLE_STATUS_YES.getCode());
  52.             }).collect(Collectors.toList());
  53.             //返回过滤后的商品信息
  54.             return productDetailDOList;
  55.         }
  56.         return productDetailList;
  57.     }
  58.     ...
  59. }
复制代码
(7)对卖家组支持的可售商品进行过滤组套商品
  1. @Service
  2. public class RecoverableServiceImpl implements RecoverableService {
  3.     ...
  4.     //进行组套商品的商品过滤(无需采购和生命周期)
  5.     private List<ProductDetailDO> suitFilter(List<ProductDetailDO> productDetailList) {
  6.         if (!CollectionUtils.isEmpty(productDetailList)) {
  7.             //1.查询哪些是组套商品,并且反向寻找到组套商品归属的item信息
  8.             List<ProductDetailDO> suitItemDOList = querySuitList(productDetailList);
  9.             //2.过滤掉无需采购的商品列表
  10.             List<ProductDetailDO> productDetailDOList = filterSuitPurchaseProduct(suitItemDOList);
  11.             //3.商品进行生命周期的查询检查,过滤不符合条件的商品
  12.             return filterSuitLifeCycle(productDetailDOList);
  13.         }
  14.         return productDetailList;
  15.     }
  16.     //通过商品明细,查询出哪些是组套商品,并输出对应的归属item数据结构
  17.     private List<ProductDetailDO> querySuitList(List<ProductDetailDO> productDetailDOList) {
  18.         //根据skuId批量查询是否组套商品
  19.         List<StackSkuRelationDO> stackSkuRelationAllList = queryStackSkuListByIds(productDetailDOList);
  20.         //没有组套商品的直接返回
  21.         if (CollectionUtils.isEmpty(stackSkuRelationAllList)) {
  22.             return productDetailDOList;
  23.         }
  24.         //返回组套商品的详情集合信息(包含item信息)
  25.         List<ProductDetailDO> itemProductList = queryProductInfoList(stackSkuRelationAllList);
  26.         //将组套商品绑定到上级对应商品下
  27.         return buildSuitBinding(itemProductList, productDetailDOList, stackSkuRelationAllList);
  28.     }
  29.     //根据skuId批量查询是否组套商品
  30.     private List<StackSkuRelationDO> queryStackSkuListByIds(List<ProductDetailDO> productDetailDOList) {
  31.         //先获取到对应的skuID列表
  32.         Set<String> skuIdList = productDetailDOList.stream().map(ProductDetailDO::getSkuId).collect(Collectors.toSet());
  33.         return productRelationRepository.pageQueryStackSkuListByIds(skuIdList);
  34.     }
  35.     //获取组套商品的详情集合信息
  36.     private List<ProductDetailDO> queryProductInfoList(List<StackSkuRelationDO> stackSkuRelationAllList) {
  37.         //获取组套商品的sku列表,通过sku列表联合查询得到对应的item信息
  38.         Set<String> stackSkuIdList = stackSkuRelationAllList.stream().map(StackSkuRelationDO::getStackSkuId).collect(Collectors.toSet());
  39.         //查询组套商品详情集合信息
  40.         return productRepository.pageQueryProductInfoList(stackSkuIdList);
  41.     }
  42.     //将组套商品绑定上
  43.     private List<ProductDetailDO> buildSuitBinding(List<ProductDetailDO> itemProductList, List<ProductDetailDO> productDetailDOList, List<StackSkuRelationDO> stackSkuRelationAllList) {
  44.         List<ProductDetailDO> productSellerRelationBOList = recoverableConverter.converterProductList(productDetailDOList);
  45.         //sku对应的组套商品详情(对应组套商品的stackSkuId)
  46.         Map<String, ProductDetailDO> productDetailMap = itemProductList.stream().collect(Collectors.toMap(ProductDetailDO::getSkuId, Function.identity()));
  47.         //组套的商品集合(一个商品下多个物料sku组装而成)
  48.         Map<String, List<StackSkuRelationDO>> stackSkuRelationMap = stackSkuRelationAllList.stream().collect(Collectors.groupingBy(StackSkuRelationDO::getSkuId));
  49.         for (ProductDetailDO productDetailDO : productSellerRelationBOList) {
  50.             //命中到了对应的组套商品
  51.             if (stackSkuRelationMap.containsKey(productDetailDO.getSkuId())) {
  52.                 List<ProductDetailDO> productDetailDOS = new ArrayList<>();
  53.                 //标记为组套商品
  54.                 productDetailDO.setProductType(2);
  55.                 //同时存储对应的组套商品详情信息
  56.                 List<StackSkuRelationDO> stackSkuRelationList = stackSkuRelationMap.get(productDetailDO.getSkuId());
  57.                 for (StackSkuRelationDO stackSkuRelationDO : stackSkuRelationList) {
  58.                     if (productDetailMap.containsKey(stackSkuRelationDO.getStackSkuId())) {
  59.                         ProductDetailDO productDetail = productDetailMap.get(stackSkuRelationDO.getStackSkuId());
  60.                         productDetailDOS.add(productDetail);
  61.                     }
  62.                 }
  63.                 productDetailDO.setProductDetailList(productDetailDOS);
  64.             }
  65.         }
  66.         return productSellerRelationBOList;
  67.     }
  68.     //过滤无需采购的组套商品
  69.     private List<ProductDetailDO> filterSuitPurchaseProduct(List<ProductDetailDO> suitItemDOList) {
  70.         //获取配置的无需采购的列表
  71.         List<ItemProcurementConfigDO> itemProcurementConfigList = productConfigRepository.queryProcurementConfigList();
  72.         //空集合判断
  73.         if (CollectionUtils.isEmpty(suitItemDOList)) {
  74.             return new ArrayList();
  75.         }
  76.         if (CollectionUtils.isEmpty(itemProcurementConfigList)) {
  77.             return suitItemDOList;
  78.         }
  79.         //集合转map,方便验证是否命中
  80.         Map<Integer, ItemProcurementConfigDO> procurementConfigMap = itemProcurementConfigList.stream().collect(Collectors.toMap(ItemProcurementConfigDO::getCategoryId, Function.identity()));
  81.         List<ProductDetailDO> productDetailDOList = new ArrayList<>(suitItemDOList.size());
  82.         for (ProductDetailDO productDetailDO : suitItemDOList) {
  83.             if (productDetailDO.getProductType().equals(2)) {
  84.                 List<ProductDetailDO> productDetailList = productDetailDO.getProductDetailList();
  85.                 //组套商品有商品不满足条件
  86.                 if (checkSuitPurchaseProduct(productDetailList, procurementConfigMap)) {
  87.                     continue;
  88.                 }
  89.             }
  90.             productDetailDOList.add(productDetailDO);
  91.         }
  92.         return productDetailDOList;
  93.     }
  94.     //进行组套商品生命周期的过滤
  95.     private List<ProductDetailDO> filterSuitLifeCycle(List<ProductDetailDO> productDetailList) {
  96.         List<ProductDetailDO> productDetailDOAllList = new ArrayList<>(productDetailList.size());
  97.         if (!CollectionUtils.isEmpty(productDetailList)) {
  98.             //查询返回生命周期的数据模型
  99.             Map<String, ItemExpriResultDTO> itemExpriResultMap = queryItemExpriMap(productDetailList);
  100.             for (ProductDetailDO productDetailDO : productDetailList) {
  101.                 if (productDetailDO.getProductType().equals(2)) {
  102.                     List<ProductDetailDO> productDetailDOList = productDetailDO.getProductDetailList();
  103.                     if (checkSuitLifeCycle(productDetailDOList, itemExpriResultMap)) {
  104.                         continue;
  105.                     }
  106.                 }
  107.                 productDetailDOAllList.add(productDetailDO);
  108.             }
  109.         }
  110.         return productDetailDOAllList;
  111.     }
  112.     ...
  113. }
复制代码
(8)将过滤后的商品数据与卖家组进行关联
  1. @Service
  2. public class RecoverableServiceImpl implements RecoverableService {
  3.     ...
  4.     //同步可采的数据入缓存
  5.     @Override
  6.     public JsonResult syncRecoverableProduct(RecoverableRequest request) {
  7.         Integer pageNo = 1;
  8.         //获取卖家类型对应的卖家组信息
  9.         List<SellerGroupResponse> sellerGroupResponses = querySellerGroupList(pageNo, request.getSellerGroupType());
  10.         while (!CollectionUtils.isEmpty(sellerGroupResponses)) {
  11.             //1.过滤卖家组的非有效状态信息数据
  12.             List<SellerGroupResponse> sellerGroupResponseList = sellerGroupFilter(sellerGroupResponses);
  13.             //2.根据卖家组获取卖家支持的可售商品列表
  14.             List<SkuSellerRelationDO> sellerRelationDOList = queryAvailableProduct(sellerGroupResponseList);
  15.             //3.查询商品信息,并过滤非自营的商品
  16.             List<ProductDetailDO> productDetailDOList = queryProductDetailList(sellerRelationDOList);
  17.             //4.进行item级别的商品过滤(无需采购和生命周期)
  18.             List<ProductDetailDO> itemFilterList = itemFilter(productDetailDOList);
  19.             //5.进行组套商品的商品过滤(无需采购和生命周期)
  20.             List<ProductDetailDO> suitFilterList = suitFilter(itemFilterList);
  21.             //6.将详情的商品sku信息绑定到卖家上
  22.             List<ProductSellerRelationBO> productSellerRelationBOList = buildBinding(sellerRelationDOList, suitFilterList);
  23.             //7.读取历史的缓存信息,对已经存在的缓存进行diff处理并刷入缓存
  24.             diffRecoverableCache(productSellerRelationBOList, sellerGroupResponses);
  25.             pageNo++;
  26.             sellerGroupResponses = querySellerGroupList(pageNo, request.getSellerGroupType());
  27.         }
  28.         return JsonResult.buildSuccess();
  29.     }
  30.     //将过滤后的商品明细绑定到卖家组上
  31.     private List<ProductSellerRelationBO> buildBinding(List<SkuSellerRelationDO> sellerRelationDOList, List<ProductDetailDO> productDetailDOList) {
  32.         //先转换集合为map,key为商品的skuId标识
  33.         Map<String, ProductDetailDO> skuInfoDOMap = productDetailDOList.stream().collect(Collectors.toMap(ProductDetailDO::getSkuId, Function.identity()));
  34.         //按卖家组ID进行分组,把下属的商品合并到一个上
  35.         Map<Long, List<SkuSellerRelationDO>> skuSellerRelationMap = sellerRelationDOList.stream().collect(Collectors.groupingBy(SkuSellerRelationDO::getSellerGroupId));
  36.         //返回的绑定卖家组和商品明细的集合对象
  37.         List<ProductSellerRelationBO> sellerRelationBOList = new ArrayList<>(sellerRelationDOList.size());
  38.         //遍历卖家和商品关系集合,开始填充商品sku信息绑定到卖家组上
  39.         for (Map.Entry<Long, List<SkuSellerRelationDO>> entry : skuSellerRelationMap.entrySet()) {
  40.             List<SkuSellerRelationDO> skuSellerRelationDOS = entry.getValue();
  41.             Long sellerGroupId = entry.getKey();
  42.             //循环绑定卖家组下的商品关系
  43.             ProductSellerRelationBO productSellerRelationBO = new ProductSellerRelationBO();
  44.             productSellerRelationBO.setSellerId(sellerGroupId);
  45.             List<ProductDetailDO> productDetailList = new ArrayList<>();
  46.             //遍历卖家组下的可售商品列表
  47.             for (SkuSellerRelationDO sellerRelationDO : skuSellerRelationDOS) {
  48.                 //查询的数据集合中 存在这个商品数据
  49.                 if (skuInfoDOMap.containsKey(sellerRelationDO.getSkuId())) {
  50.                     ProductDetailDO productDetailDO = skuInfoDOMap.get(sellerRelationDO.getSkuId());
  51.                     //绑定数据到卖家组上
  52.                     productDetailList.add(productDetailDO);
  53.                 }
  54.             }
  55.             productSellerRelationBO.setProductDetailList(productDetailList);
  56.             sellerRelationBOList.add(productSellerRelationBO);
  57.         }
  58.         return sellerRelationBOList;
  59.     }
  60.     ...
  61. }
复制代码
 
(9)读取缓存与刷入缓存的逻辑
  1. @Service
  2. public class RecoverableServiceImpl implements RecoverableService {
  3.     @Autowired
  4.     private RedisReadWriteManager redisReadWriteManager;
  5.     ...
  6.     //对已经缓存的历史数据进行diff处理,处理缓存变更
  7.     private void diffRecoverableCache(List<ProductSellerRelationBO> productSellerRelationBOList, List<SellerGroupResponse> sellerGroupResponses) {
  8.         //1.获取卖家组ID集合
  9.         Set<Long> sellerGroupIdList = sellerGroupResponses.stream().map(SellerGroupResponse::getSellerGroupId).collect(Collectors.toSet());
  10.         //2.数据差集比较,并刷入缓存差异信息
  11.         diffCache(sellerGroupIdList, productSellerRelationBOList);
  12.     }
  13.     //开始进行数据差集的处理
  14.     private void diffCache(Set<Long> sellerIdList, List<ProductSellerRelationBO> productSellerRelationBOList) {
  15.         //1.批量查询缓存
  16.         Map<Long, List<String>> redisSetMap = redisReadWriteManager.getRedisSortedSet(sellerIdList, AbstractRedisKeyConstants::getSellerTypePurchaseSkuZsetKey);
  17.         //转换缓存的值为具体的对象
  18.         Map<Long, Map<String, ProductDetailDO>> productSellerRelationBOMap = redisManagerRepository.converterProductSellerCache(redisSetMap);
  19.         //进行数据差集处理
  20.         Map<String, RedisSortedSetCache> diffSortedSetCache = redisManagerRepository.diffProduct(productSellerRelationBOList, productSellerRelationBOMap, AbstractRedisKeyConstants::getSellerTypePurchaseSkuZsetKey);
  21.         //执行数据缓存更新
  22.         redisReadWriteManager.flushIncrSortedSetMap(diffSortedSetCache);
  23.     }
  24.     ...
  25. }
  26. @Service
  27. public class RedisReadWriteManager {
  28.     ...
  29.     //批量获取Sorted Set
  30.     public <T> Map<T, List<String>> getRedisSortedSet(Collection<T> keys, Function<T, String> getRedisKeyFunction) {
  31.         if (CollectionUtils.isEmpty(keys)) {
  32.             return Maps.newHashMap();
  33.         }
  34.         Map<T, List<String>> responseMap = Maps.newHashMap();
  35.         for (T key : keys) {
  36.             String redisKey = getRedisKeyFunction.apply(key);
  37.             responseMap.put(key, allRedisSortedSet(redisKey));
  38.         }
  39.         return responseMap;
  40.     }
  41.     //获取Sorted Set的所有数据
  42.     private List<String> allRedisSortedSet(String redisKey) {
  43.         Set<String> strings = redisCache.zrangeByScore(redisKey, 0L, Long.MAX_VALUE, 0L, Long.MAX_VALUE);
  44.         List<String> sortedList = CollectionUtils.isEmpty(strings) ? new ArrayList<>() : new LinkedList<>(strings);
  45.         return sortedList;
  46.     }
  47.     //刷新有序缓存
  48.     public void flushIncrSortedSetMap(Map<String, RedisSortedSetCache> sortedSetSourceMap) {
  49.         for (Map.Entry<String, RedisSortedSetCache> entry : sortedSetSourceMap.entrySet()) {
  50.             //获取到缓存的key标志信息
  51.             String key = entry.getKey();
  52.             //缓存操作对象,每个卖家缓存一份
  53.             RedisSortedSetCache sortedSetSource = entry.getValue();
  54.             if (sortedSetSource.getDeleteKey()) {
  55.                 redisCache.delete(key);
  56.                 continue;
  57.             }
  58.             if (MapUtils.isNotEmpty(sortedSetSource.getAddMap())) {
  59.                 addSortedSet(sortedSetSource.getAddMap(), key);
  60.             }
  61.             if (!CollectionUtils.isEmpty(sortedSetSource.getDeleteMemberSet())) {
  62.                 removeSortedSet(key, sortedSetSource.getDeleteMemberSet());
  63.             }
  64.         }
  65.     }
  66.     //添加Sorted Set
  67.     public void addSortedSet(Map<String, Double> addMap, String redisKey) {
  68.         if (MapUtils.isEmpty(addMap)) {
  69.             return;
  70.         }
  71.         for (Map.Entry<String, Double> entry : addMap.entrySet()) {
  72.             String product = entry.getKey();
  73.             Double score = entry.getValue();
  74.             redisCache.zadd(redisKey, product, score);
  75.         }
  76.     }
  77.     //删除Sorted Set
  78.     public void removeSortedSet(String redisKey, Set<String> memberSet) {
  79.         redisCache.zremove(redisKey, memberSet.toArray(new String[]{}));
  80.     }
  81.     ...
  82. }
复制代码
(10)卖家组支持的可采商品与缓存的diff逻辑
  1. @Repository
  2. public class RedisManagerRepository {
  3.     @Autowired
  4.     private SegmentIDGen segmentIDGen;
  5.     ...
  6.     //将缓存的数据转换为实体对象
  7.     public Map<Long, Map<String, ProductDetailDO>> converterProductSellerCache(Map<Long, List<String>> redisSetMap) {
  8.         Map<Long, Map<String, ProductDetailDO>> productSellerRelationBOMap = new HashMap<>(redisSetMap.size());
  9.         if (!CollectionUtils.isEmpty(redisSetMap)) {
  10.             for (Map.Entry<Long, List<String>> entry : redisSetMap.entrySet()) {
  11.                 List<String> productSellerList = entry.getValue();
  12.                 Map<String, ProductDetailDO> productDetailMap = new HashMap<>(productSellerList.size());
  13.                 for (String content : productSellerList) {
  14.                     ProductDetailDO productDetailDO = JSONObject.parseObject(content, ProductDetailDO.class);
  15.                     productDetailMap.put(productDetailDO.getSkuId(), productDetailDO);
  16.                 }
  17.                 productSellerRelationBOMap.put(entry.getKey(), productDetailMap);
  18.             }
  19.         }
  20.         return productSellerRelationBOMap;
  21.     }
  22.     //对缓存差集的数据进行处理
  23.     public <T> Map<String, RedisSortedSetCache> diffProduct(List<ProductSellerRelationBO> productSellerRelationBOList,
  24.             Map<Long, Map<String, ProductDetailDO>> productSellerCacheMap, Function<Long, String> getRedisKeyFunction) {
  25.         Map<String, RedisSortedSetCache> redisSortedSetCacheMap = new HashMap<>();
  26.         //1.处理缓存中需要新增的数据,删除数据
  27.         Map<Long, ProductSellerRelationBO> productSellerRelationResidueMap = diffCacheAddOrDelete(productSellerRelationBOList, productSellerCacheMap, redisSortedSetCacheMap, getRedisKeyFunction);
  28.         //2.处理缓存中不存在的卖家数据,新增处理
  29.         diffAddSellerCache(productSellerRelationResidueMap, redisSortedSetCacheMap, getRedisKeyFunction);
  30.         //3.处理缓存中存在的卖家数据,结果不存在,删除处理
  31.         diffDeleteSellerCache(productSellerCacheMap, redisSortedSetCacheMap, getRedisKeyFunction);
  32.         return redisSortedSetCacheMap;
  33.     }
  34.     //处理缓存中需要新增的数据,删除数据
  35.     private <T> Map<Long, ProductSellerRelationBO> diffCacheAddOrDelete(List<ProductSellerRelationBO> productSellerRelationBOList,
  36.             Map<Long, Map<String, ProductDetailDO>> productSellerCacheMap, Map<String, RedisSortedSetCache> redisSortedSetCacheMap, Function<Long, String> getRedisKeyFunction) {
  37.         Map<Long, ProductSellerRelationBO> productSellerRelationResidueMap = new HashMap<>(productSellerRelationBOList.size());
  38.         for (ProductSellerRelationBO productSellerRelation : productSellerRelationBOList) {
  39.             RedisSortedSetCache redisSortedSetCache = new RedisSortedSetCache();
  40.             Long sellerId = productSellerRelation.getSellerId();
  41.             String redisKey = getRedisKeyFunction.apply(sellerId);
  42.             //命中了缓存的数据,开始进行差集处理
  43.             if (productSellerCacheMap.containsKey(sellerId)) {
  44.                 //获取当前这个卖家下的缓存商品信息,key为商品sku
  45.                 Map<String, ProductDetailDO> productDetailDOMap = productSellerCacheMap.get(sellerId);
  46.                 //卖家的处理后的可售商品列表
  47.                 List<ProductDetailDO> productDetailList = productSellerRelation.getProductDetailList();
  48.                 //处理返回差异的数据结果,需新增或者删除的数据集合
  49.                 for (ProductDetailDO productDetailDO : productDetailList) {
  50.                     //命中了则说明无差异,不处理,从集合中移除
  51.                     if (!CollectionUtils.isEmpty(productDetailDOMap) && productDetailDOMap.containsKey(productDetailDO.getSkuId())) {
  52.                         productDetailDOMap.remove(productDetailDO.getSkuId());
  53.                         continue;
  54.                     }
  55.                     //未命中,说明这个数据缓存中不存在,做新增处理
  56.                     redisSortedSetCache.getAddMap().put(JSONObject.toJSON(productDetailDO).toString(), getSortedSetScore(redisKey));
  57.                 }
  58.                 //遍历处理完成之后,缓存中还有多余的对象都属于无效数据,需要删除
  59.                 if (!CollectionUtils.isEmpty(productDetailDOMap)) {
  60.                     for (Map.Entry<String, ProductDetailDO> entry : productDetailDOMap.entrySet()) {
  61.                         redisSortedSetCache.getDeleteMemberSet().add(JSONObject.toJSON(entry.getValue()).toString());
  62.                     }
  63.                 }
  64.                 //设置到需要处理得缓存对象中
  65.                 redisSortedSetCacheMap.put(redisKey, redisSortedSetCache);
  66.                 //删除处理掉的缓存对象
  67.                 productSellerCacheMap.remove(sellerId);
  68.             } else {
  69.                 //未命中缓存的 都是新增数据
  70.                 productSellerRelationResidueMap.put(sellerId, productSellerRelation);
  71.             }
  72.         }
  73.         return productSellerRelationResidueMap;
  74.     }
  75.     //处理缓存中不存在的卖家数据,新增处理
  76.     private void diffAddSellerCache(Map<Long, ProductSellerRelationBO> productSellerRelationMap,
  77.             Map<String, RedisSortedSetCache> redisSortedSetCacheMap, Function<Long, String> getRedisKeyFunction) {
  78.         Iterator<Map.Entry<Long, ProductSellerRelationBO>> iterator = productSellerRelationMap.entrySet().iterator();
  79.         //对处理缓存差集后,还剩余的未处理数据做新增处理
  80.         while (iterator.hasNext()) {
  81.             Map.Entry<Long, ProductSellerRelationBO> entrys = iterator.next();
  82.             ProductSellerRelationBO productSellerRelation = entrys.getValue();
  83.             RedisSortedSetCache redisSortedSetCache = new RedisSortedSetCache();
  84.             Long key = entrys.getKey();
  85.             String redisKey = getRedisKeyFunction.apply(key);
  86.             //卖家的处理后的可售商品列表
  87.             List<ProductDetailDO> productDetailList = productSellerRelation.getProductDetailList();
  88.             for (ProductDetailDO productDetailDO : productDetailList) {
  89.                 redisSortedSetCache.getAddMap().put(JSONObject.toJSON(productDetailDO).toString(), getSortedSetScore(redisKey));
  90.             }
  91.             //设置到需要处理得缓存对象中
  92.             redisSortedSetCacheMap.put(redisKey, redisSortedSetCache);
  93.         }
  94.     }
  95.     //处理缓存中存在的卖家数据,结果不存在,删除处理
  96.     private void diffDeleteSellerCache(Map<Long, Map<String, ProductDetailDO>> productSellerCacheMap,
  97.             Map<String, RedisSortedSetCache> redisSortedSetCacheMap, Function<Long, String> getRedisKeyFunction) {
  98.         //当可售的列表中,不存在缓存已经存在的数据列表,说明缓存已经无效,需要删除该对应的key下的缓存信息
  99.         if (!CollectionUtils.isEmpty(productSellerCacheMap)) {
  100.             for (Map.Entry<Long, Map<String, ProductDetailDO>> entry : productSellerCacheMap.entrySet()) {
  101.                 Long key = entry.getKey();
  102.                 Map<String, ProductDetailDO> value = entry.getValue();
  103.                 if (CollectionUtils.isEmpty(value)) {
  104.                     continue;
  105.                 }
  106.                 String redisKey = getRedisKeyFunction.apply(key);
  107.                 RedisSortedSetCache redisSortedSetCache = new RedisSortedSetCache();
  108.                 redisSortedSetCache.setDeleteKey(Boolean.TRUE);
  109.                 //设置到需要处理得缓存对象中
  110.                 redisSortedSetCacheMap.put(redisKey, redisSortedSetCache);
  111.             }
  112.         }
  113.     }
  114.     ...
  115.     //新增缓存时需要获取每个缓存key存储的权重值
  116.     public Double getSortedSetScore(String cacheKey) {
  117.         //新增可采商品缓存时基于db的分段发号
  118.         Long autoNo = segmentIDGen.genNewNo(cacheKey);
  119.         return Double.valueOf(autoNo);
  120.     }
  121. }
复制代码
(11)基于DB的分段发号器组件
一.号段内存缓冲组件SegmentBuffer
  1. //号段内存缓冲组件
  2. @Data
  3. @Accessors(chain = true)
  4. public class SegmentBuffer {
  5.     //线程是否在运行中
  6.     private final AtomicBoolean threadRunning;
  7.     private final ReadWriteLock lock;
  8.     private String bizTag;
  9.     //双buffer
  10.     private Segment[] segments;
  11.     //当前的使用的segment的index
  12.     private volatile int currentPos;
  13.     //下一个segment是否处于可切换状态
  14.     private volatile boolean nextReady;
  15.     //是否初始化完成
  16.     private volatile boolean initOk;
  17.     private volatile int step;
  18.     private volatile int minStep;
  19.     private volatile long updateTimestamp;
  20.     public SegmentBuffer() {
  21.         segments = new Segment[]{new Segment(this), new Segment(this)};
  22.         currentPos = 0;
  23.         nextReady = false;
  24.         initOk = false;
  25.         threadRunning = new AtomicBoolean(false);
  26.         lock = new ReentrantReadWriteLock();
  27.     }
  28.     public Segment getCurrent() {
  29.         return segments[currentPos];
  30.     }
  31.     public Lock rLock() {
  32.         return lock.readLock();
  33.     }
  34.     public Lock wLock() {
  35.         return lock.writeLock();
  36.     }
  37.     public int nextPos() {
  38.         return (currentPos + 1) % 2;
  39.     }
  40.     public void switchPos() {
  41.         currentPos = nextPos();
  42.     }
  43.     ...
  44. }
复制代码
  1. @Component
  2. public class SegmentIDCache implements ApplicationListener<ContextRefreshedEvent> {
  3.     private final Map<String, SegmentBuffer> cache = new ConcurrentHashMap<>();
  4.     @Resource
  5.     private LeafAllocNoMapper leafAllocNoMapper;
  6.     private volatile boolean initOk = false;
  7.     @Override
  8.     public void onApplicationEvent(ContextRefreshedEvent event) {
  9.         checkAndInit();
  10.     }
  11.     //初始化数据
  12.     private void checkAndInit() {
  13.         if (!initOk) {
  14.             synchronized (this) {
  15.                 if (!initOk) {
  16.                     log.info("Init ...");
  17.                     //确保加载到kv后才初始化成功
  18.                     updateCacheFromDb();
  19.                     initOk = true;
  20.                     log.info("Init Ok ...");
  21.                 }
  22.             }
  23.         }
  24.     }
  25.     public boolean isInitOk() {
  26.         return initOk;
  27.     }
  28.     public boolean containsKey(String bizCode) {
  29.         checkAndInit();
  30.         return cache.containsKey(bizCode);
  31.     }
  32.     public SegmentBuffer getValue(String bizCode) {
  33.         checkAndInit();
  34.         return cache.get(bizCode);
  35.     }
  36.     //单个初始化加载
  37.     public void updateCacheFromDb(String bizCode) {
  38.         log.info("update cache from db");
  39.         try {
  40.             LeadAllocDO dbBizCodes = leafAllocNoMapper.findByBizTag(bizCode);
  41.             if (Objects.isNull(dbBizCodes)) {
  42.                 return;
  43.             }
  44.             SegmentBuffer buffer = new SegmentBuffer();
  45.             buffer.setBizTag(bizCode);
  46.             Segment segment = buffer.getCurrent();
  47.             segment.setValue(new AtomicLong(0));
  48.             segment.setMax(0);
  49.             segment.setStep(0);
  50.             cache.put(bizCode, buffer);
  51.             log.info("Add bizCode {} from db to IdCache, SegmentBuffer {}", bizCode, buffer);
  52.         } catch (Exception e) {
  53.             log.warn("update cache from db exception", e);
  54.         } finally {
  55.             log.info("updateCacheFromDb,cost:{}", 0);
  56.         }
  57.     }
  58.     //更新缓存key
  59.     private void updateCacheFromDb() {
  60.         log.info("update cache from db");
  61.         try {
  62.             List<String> dbBizCodes = leafAllocNoMapper.listAllBizTag();
  63.             if (CollectionUtils.isEmpty(dbBizCodes)) {
  64.                 return;
  65.             }
  66.             List<String> cacheBiz = new ArrayList<>(cache.keySet());
  67.             Set<String> insertBizSet = new HashSet<>(dbBizCodes);
  68.             Set<String> removeBizSet = new HashSet<>(cacheBiz);
  69.             //db中新加的tags灌进cache
  70.             for (String tmp : cacheBiz) {
  71.                 insertBizSet.remove(tmp);
  72.             }
  73.             for (String bizCode : insertBizSet) {
  74.                 SegmentBuffer buffer = new SegmentBuffer();
  75.                 buffer.setBizTag(bizCode);
  76.                 Segment segment = buffer.getCurrent();
  77.                 segment.setValue(new AtomicLong(0));
  78.                 segment.setMax(0);
  79.                 segment.setStep(0);
  80.                 cache.put(bizCode, buffer);
  81.                 log.info("Add bizCode {} from db to IdCache, SegmentBuffer {}", bizCode, buffer);
  82.             }
  83.             for (String tmp : dbBizCodes) {
  84.                 removeBizSet.remove(tmp);
  85.             }
  86.             for (String tag : removeBizSet) {
  87.                 cache.remove(tag);
  88.                 log.info("Remove tag {} from IdCache", tag);
  89.             }
  90.         } catch (Exception e) {
  91.             log.warn("update cache from db exception", e);
  92.         } finally {
  93.             log.info("updateCacheFromDb,cost:{}", 0);
  94.         }
  95.     }
  96. }
复制代码
二.号段ID生成器组件SegmentIDGen
  1. //号段ID生成器组件
  2. @Service
  3. public class SegmentIDGenImpl implements SegmentIDGen {
  4.     //下一次异步更新比率因子
  5.     public static final double NEXT_INIT_FACTOR = 0.9;
  6.     //最大步长不超过100,0000
  7.     private static final int MAX_STEP = 1000000;
  8.     //默认一个Segment会维持的时间为15分钟
  9.     //如果在15分钟内Segment就消耗完了,则步长要扩容一倍,但不能超过MAX_STEP
  10.     //如果在超过15*2=30分钟才将Segment消耗完,则步长要缩容一倍,但不能低于MIN_STEP,MIN_STEP的值为数据库中初始的step字段值
  11.     private static final long SEGMENT_DURATION = 15 * 60 * 1000L;
  12.     //更新因子
  13.     //更新因子=2时,表示成倍扩容或者折半缩容
  14.     private static final int EXPAND_FACTOR = 2;
  15.     private final ExecutorService threadPoolExecutor = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new UpdateThreadFactory());
  16.     @Autowired
  17.     private LeafAllocNoRepository leafAllocNoRepository;
  18.     @Resource
  19.     private SegmentIDCache cache;
  20.     //生成新的ID
  21.     @Override
  22.     public Long genNewNo(String bizTag) {
  23.         if (!cache.isInitOk()) {
  24.             throw new RuntimeException("not init");
  25.         }
  26.         //如果没有,此时需要初始化一个
  27.         if (!cache.containsKey(bizTag)) {
  28.             leafAllocNoRepository.insertLeadAlloc(bizTag);
  29.             cache.updateCacheFromDb(bizTag);
  30.         }
  31.         SegmentBuffer buffer = cache.getValue(bizTag);
  32.         if (!buffer.isInitOk()) {
  33.             synchronized (buffer) {
  34.                 if (!buffer.isInitOk()) {
  35.                     try {
  36.                         updateSegmentFromDb(bizTag, buffer.getCurrent());
  37.                         log.info("Init buffer. Update leafkey {} {} from db", bizTag, buffer.getCurrent());
  38.                         buffer.setInitOk(true);
  39.                     } catch (Exception e) {
  40.                         log.warn("Init buffer {} exception", buffer.getCurrent(), e);
  41.                         throw new RuntimeException("init error:" + bizTag);
  42.                     }
  43.                 }
  44.             }
  45.         }
  46.         return getIdFromSegmentBuffer(buffer);
  47.     }
  48.     //从segment缓冲中获取id
  49.     private Long getIdFromSegmentBuffer(SegmentBuffer buffer) {
  50.         while (true) {
  51.             buffer.rLock().lock();
  52.             try {
  53.                 final Segment segment = buffer.getCurrent();
  54.                 if (!buffer.isNextReady() && (segment.getIdle() < NEXT_INIT_FACTOR * segment.getStep())
  55.                         && buffer.getThreadRunning().compareAndSet(false, true)) {
  56.                     asyncUpdate(buffer);
  57.                 }
  58.                 long value = segment.getValue().getAndIncrement();
  59.                 if (value < segment.getMax()) {
  60.                     return value;
  61.                 }
  62.             } finally {
  63.                 buffer.rLock().unlock();
  64.             }
  65.             //获取的value,大于max,则等待其他线程更新完毕。最多等待100s
  66.             waitAndSleep(buffer);
  67.             buffer.wLock().lock();
  68.             try {
  69.                 final Segment segment = buffer.getCurrent();
  70.                 long value = segment.getValue().getAndIncrement();
  71.                 if (value < segment.getMax()) {
  72.                     return value;
  73.                 }
  74.                 if (buffer.isNextReady()) {
  75.                     buffer.switchPos();
  76.                     buffer.setNextReady(false);
  77.                 } else {
  78.                     log.error("Both two segments in {} are not ready!", buffer);
  79.                     throw new RuntimeException("next not ready");
  80.                 }
  81.             } finally {
  82.                 buffer.wLock().unlock();
  83.             }
  84.         }
  85.     }
  86.     //异步更新初始化
  87.     private void asyncUpdate(SegmentBuffer buffer) {
  88.         long submitTime = System.currentTimeMillis();
  89.         threadPoolExecutor.execute(() -> {
  90.             long executeTime = System.currentTimeMillis();
  91.             Segment next = buffer.getSegments()[buffer.nextPos()];
  92.             boolean updateOk = false;
  93.             try {
  94.                 updateSegmentFromDb(buffer.getBizTag(), next);
  95.                 updateOk = true;
  96.             } catch (Exception e) {
  97.                 log.warn("{} updateSegmentFromDb exception", buffer.getBizTag(), e);
  98.             } finally {
  99.                 long finishTime = System.currentTimeMillis();
  100.                 log.info("update segment {} from db {}。st:{}, et:{}, ft:{}", buffer.getBizTag(), next, submitTime, executeTime, finishTime);
  101.                 if (updateOk) {
  102.                     buffer.wLock().lock();
  103.                     buffer.setNextReady(true);
  104.                     buffer.getThreadRunning().set(false);
  105.                     buffer.wLock().unlock();
  106.                 } else {
  107.                     buffer.getThreadRunning().set(false);
  108.                 }
  109.             }
  110.         });
  111.     }
  112.     //自旋10000次之后,睡眠10毫秒
  113.     private void waitAndSleep(SegmentBuffer buffer) {
  114.         int roll = 0;
  115.         while (buffer.getThreadRunning().get()) {
  116.             roll += 1;
  117.             if (roll > 10000) {
  118.                 try {
  119.                     TimeUnit.MILLISECONDS.sleep(10);
  120.                     break;
  121.                 } catch (InterruptedException e) {
  122.                     log.warn("Thread {} Interrupted", Thread.currentThread().getName());
  123.                     break;
  124.                 }
  125.             }
  126.         }
  127.     }
  128.     //从db中更新号段
  129.     public void updateSegmentFromDb(String bizTag, Segment segment) {
  130.         SegmentBuffer buffer = segment.getBuffer();
  131.         LeadAllocDO leadAllocDO;
  132.         if (!buffer.isInitOk()) {
  133.             leadAllocDO = leafAllocNoRepository.updateMaxIdAndGet(bizTag);
  134.             buffer.setStep(leadAllocDO.getStep());
  135.             buffer.setMinStep(leadAllocDO.getStep());
  136.         } else if (buffer.getUpdateTimestamp() == 0) {
  137.             leadAllocDO = leafAllocNoRepository.updateMaxIdAndGet(bizTag);
  138.             buffer.setUpdateTimestamp(System.currentTimeMillis());
  139.             buffer.setStep(leadAllocDO.getStep());
  140.             buffer.setMinStep(leadAllocDO.getStep());
  141.         } else {
  142.             int nextStep = calculateNextStep(bizTag, buffer);
  143.             leadAllocDO = leafAllocNoRepository.updateMaxIdByDynamicStepAndGet(bizTag, nextStep);
  144.             buffer.setUpdateTimestamp(System.currentTimeMillis());
  145.             buffer.setStep(nextStep);
  146.             buffer.setMinStep(leadAllocDO.getStep());
  147.         }
  148.         // must set value before set max
  149.         long value = leadAllocDO.getMaxId() - buffer.getStep();
  150.         segment.getValue().set(value);
  151.         segment.setMax(leadAllocDO.getMaxId());
  152.         segment.setStep(buffer.getStep());
  153.         log.info("updateSegmentFromDb, bizTag: {}, cost:0, segment:{}", bizTag, segment);
  154.     }
  155.     //计算新的步长
  156.     private int calculateNextStep(String bizCode, SegmentBuffer buffer) {
  157.         long duration = System.currentTimeMillis() - buffer.getUpdateTimestamp();
  158.         int nextStep = buffer.getStep();
  159.         if (duration < SEGMENT_DURATION) {
  160.             nextStep = Math.min(MAX_STEP, nextStep * EXPAND_FACTOR);
  161.         } else if (duration < SEGMENT_DURATION * EXPAND_FACTOR) {
  162.             // do nothing with nextStep
  163.         } else {
  164.             nextStep = Math.max(buffer.getMinStep(), nextStep / EXPAND_FACTOR);
  165.         }
  166.         log.info("leafKey[{}], step[{}], duration[{}mins], nextStep[{}]", bizCode, buffer.getStep(), String.format("%.2f", ((double) duration / (1000 * 60))), nextStep);
  167.         return nextStep;
  168.     }
  169.     public static class UpdateThreadFactory implements ThreadFactory {
  170.         private static int threadInitNumber = 0;
  171.         private static synchronized int nextThreadNum() {
  172.             return threadInitNumber++;
  173.         }
  174.         @Override
  175.         public Thread newThread(Runnable r) {
  176.             return new Thread(r, "Thread-Segment-Update-" + nextThreadNum());
  177.         }
  178.     }
  179. }
复制代码
 
3.定时同步可补商品
(1)时序图
(2)流程图
(3)代码实现
 
(1)时序图
3.png
(2)流程图
4.png
一.分⻚查询卖家组信息。每次处理完⼀批数据后,剩余数据会继续通过下⼀⻚来查询获取。
 
二.根据卖家组和商品的关系表查询出卖家组所⽀持的商品。查询商品与卖家组关系表sku_seller_relation,过滤掉⾮⾃营的商品。
 
三.根据查询返回的item列表批量查询得到商品的item信息。查询过程需要商品表item_info关联查询商品扩展属性表attribute_extend,然后填充屏蔽微仓的扩展JSON信息,并对该屏蔽的卖家ID进⾏过滤商品。
 
四.遍历商品检查商品状态是否为试销。商品状态:1准备上架、2试销上架、3上架、4预下架、5下架、6停售。如果是试销商品,则查询当前商品归属的仓是否有试销标识。如果不是试销商品或试销商品所属的仓没有试销标识,则进⾏过滤。
 
五.根据商品的存储条件对归属仓的存储条件进⾏匹配。只有商品的存储条件和归属仓的存储条件匹配了才允许补货,存储条件即sellerLableList卖家标签:1常温、2冷藏、3冷冻、4⽔产。
 
六.进⾏组套商品验证。先通过sku批量查询组套商品与SKU关系表stack_sku_relation,获取到每个sku下的原料以及普通商品信息,然后对每个商品进⾏试销判断以及存储条件处理,两者都满⾜才允许补货。
 
七.对已存在的缓存数据和当前这次同步处理后的数据进⾏差集diff处理。发⽣变化的数据才需要刷⼊缓存,比如新增的或者⽆效的数据。
 
八.构建缓存模型,对可补的商品信息进⾏缓存。key为'前缀标识+卖家ID',value为'可补的sku列表'。
 
(3)代码实现
  1. @Component
  2. public class CompensationJobHandler {
  3.     @DubboReference(version = "1.0.0")
  4.     private CompensationApi compensationApi;
  5.     @XxlJob("syncCompensationProduct")
  6.     public void syncCompensationProduct(CompensationRequest request) {
  7.         XxlJobHelper.log("sync available product job starting...");
  8.         JsonResult result = compensationApi.syncCompensationProduct(request);
  9.         XxlJobHelper.log("sync available product job end, result:{}", result);
  10.     }
  11. }
  12. @DubboService(version = "1.0.0", interfaceClass = CompensationApi.class, retries = 0)
  13. public class CompensationApiImpl implements CompensationApi {
  14.     @Resource
  15.     private CompensationService compensationService;
  16.     //同步可补商品
  17.     @Override
  18.     public JsonResult syncCompensationProduct(CompensationRequest request) {
  19.         try {
  20.             return compensationService.syncCompensationProduct(request);
  21.         } catch (ProductBizException e) {
  22.             log.error("biz error: ", e);
  23.             return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
  24.         } catch (Exception e) {
  25.             log.error("system error: ", e);
  26.             return JsonResult.buildError(e.getMessage());
  27.         }
  28.     }
  29. }
  30. @Service
  31. public class CompensationServiceImpl implements CompensationService {
  32.     ...
  33.     //同步可补的数据入缓存
  34.     @Override
  35.     public JsonResult syncCompensationProduct(CompensationRequest request) {
  36.         //分页查询商品信息,处理商品可补的数据
  37.         Integer pageNo = 1;
  38.         List<SellerGroupResponse> sellerGroupResponses = querySellerGroupList(pageNo, request.getSellerGroupType());
  39.         while (!CollectionUtils.isEmpty(sellerGroupResponses)) {
  40.             //1.过滤卖家组的非有效状态信息数据
  41.             List<SellerGroupResponse> sellerGroupResponseList = sellerGroupFilter(sellerGroupResponses);
  42.             //2.根据卖家组获取卖家支持的可售商品列表
  43.             List<SkuSellerRelationDO> sellerRelationDOList = queryAvailableProduct(sellerGroupResponseList);
  44.             //3.查询商品信息,并过滤非自营的商品,填充关于商品的扩展信息
  45.             List<ProductDetailDO> productDetailDOList = queryProductDetailList(sellerRelationDOList);
  46.             //4.解析屏蔽微仓的扩展json,对屏蔽的卖家ID进行过滤,并将详情的商品sku信息绑定到卖家上
  47.             List<ProductSellerRelationBO> sellerFilterList = sellerFilter(productDetailDOList, sellerRelationDOList, sellerGroupResponses);
  48.             //5.普通商品过滤(试销品过滤,存储条件过滤)
  49.             List<ProductSellerRelationBO> itemFilterList = itemFilter(sellerFilterList);
  50.             //6.组套商品过滤(试销品过滤,存储条件过滤)
  51.             List<ProductSellerRelationBO> suitFilterList = suitFilter(itemFilterList);
  52.             //7.读取历史的缓存信息,对已经存在的缓存进行diff处理,处理新增或者修改的数据更新缓存
  53.             diffRecoverableCache(suitFilterList, sellerGroupResponses);
  54.             pageNo++;
  55.             sellerGroupResponses = querySellerGroupList(pageNo, request.getSellerGroupType());
  56.         }
  57.         return JsonResult.buildSuccess();
  58.     }
  59.     ...
  60. }
复制代码
 
4.定时同步可售商品
(1)时序图
(2)流程图
(3)代码实现
 
(1)时序图
5.png
(2)流程图
6.png
一.分页查询卖家组信息,调⽤查询卖家组信息接⼝,返回卖家组信息列表。
 
二.对返回的卖家组列表进行过滤,过滤无效状态的卖家组。
 
三.根据卖家组列表获取⽀撑这些卖家组所⽀持售卖的商品,通过商品与卖家组关系表sku_seller_relation查询出卖家组⽀持售卖的商品。查询时匹配字段relation_type关系类型,只获取可售商品。relation_type关系类型有:1可售、2屏蔽。
 
四.根据商品卖家库存关系表查询得到卖家组⽀持售卖的库存充⾜的商品。商品卖家库存关系表是sku_stock_seller_relation,查询时匹配库存数量stock_num > 0,且seller_type卖家类型是⾃营的商品。seller_type卖家类型有:1⾃营、2POP。
 
五.通过商品与卖家组关系表和商品卖家库存关系表构建卖家可售商品信息。商品与卖家组关系表是sku_seller_relation,商品卖家库存关系表是sku_stock_seller_relation。
 
六.根据商品属性扩展表查询到商品的属性内容进行过滤,也就是对商品中屏蔽卖家的扩展信息进⾏筛选。商品属性扩展表是attribute_extend,商品的属性内容表是attribute_content。
 
七.读取历史的缓存信息,对已经存在的缓存进⾏diff处理,需要处理新增或者修改的数据更新缓存。
 
八.构建缓存模型,对可售的商品数据进⾏缓存。卖家的缓存的模型对象为:key为'前缀标识+卖家ID',value为'可售skuId'。卖家类型的缓存模型对象为:key为'前缀标识+卖家类型',value为'可售skuId'。
 
(3)代码实现
  1. @Component
  2. public class AvailableJobHandler {
  3.     @DubboReference(version = "1.0.0")
  4.     private AvailableApi availableApi;
  5.     @XxlJob("syncAvailableProduct")
  6.     public void syncAvailableProduct() {
  7.         XxlJobHelper.log("sync available product job starting...");
  8.         JsonResult result = availableApi.syncAvailableProduct(null);
  9.         XxlJobHelper.log("sync available product job end, result:{}", result);
  10.     }
  11. }
  12. @DubboService(version = "1.0.0", interfaceClass = AvailableApi.class, retries = 0)
  13. public class AvailableApiImpl implements AvailableApi {
  14.     @Resource
  15.     private AvailableService availableService;
  16.     //同步可售商品
  17.     @Override
  18.     public JsonResult syncAvailableProduct(AvailableRequest request) {
  19.         try {
  20.             Boolean success = availableService.syncAvailableProduct(request);
  21.             return JsonResult.buildSuccess(success);
  22.         } catch (ProductBizException e) {
  23.             log.error("biz error: request={}", JSON.toJSONString(request), e);
  24.             return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
  25.         } catch (Exception e) {
  26.             log.error("system error: request={}", JSON.toJSONString(request), e);
  27.             return JsonResult.buildError(e.getMessage());
  28.         }
  29.     }
  30. }
  31. @Service
  32. public class AvailableServiceImpl implements AvailableService {
  33.     ...
  34.     //同步可售商品
  35.     @Override
  36.     public Boolean syncAvailableProduct(AvailableRequest request) {
  37.         //分页查询商品信息,处理商品可售的数据
  38.         Integer pageNo = 1;
  39.         //1.获取卖家组信息列表
  40.         List<SellerGroupResponse> sellerGroupList = querySellerGroupList(pageNo, request.getSellerGroupType());
  41.         //自营还是POP可售的skuId集合
  42.         Map<Integer, List<String>> sellerTypeSkuIdMap = new HashMap<>(2);
  43.         while (!CollectionUtils.isEmpty(sellerGroupList)) {
  44.             //2.对卖家组状态非有效的进行过滤
  45.             List<SellerGroupResponse> effectiveSellerGroupList = sellerGroupFilter(sellerGroupList);
  46.             //3.根据卖家组列表获取卖家组所支持售卖的商品
  47.             List<SkuSellerRelationDTO> saleProductList = querySaleProductList(effectiveSellerGroupList);
  48.             //4.获取自营可售商品的且库存充足的信息
  49.             Map<Long, String> sellerInStockMap = querySellerInStockProductMap(saleProductList);
  50.             //5.构建卖家可售商品信息
  51.             Map<Long, List<String>> sellerSaleProductMap = buildSellerAvailableProduct(sellerInStockMap, effectiveSellerGroupList, saleProductList);
  52.             //6.对商品中屏蔽卖家的扩展信息进行筛选
  53.             sellerSaleProductMap = sellerFilter(sellerSaleProductMap, saleProductList);
  54.             //7.合并卖家类型的可售商品
  55.             mergeSellerTypeSkuIdMap(sellerTypeSkuIdMap, saleProductList, sellerSaleProductMap);
  56.             //8.读取历史的缓存信息,对已经存在的缓存进行diff处理,需要处理新增或者修改的数据更新缓存
  57.             //构建数据模型,将卖家可售商品缓存起来 缓存结构 key:"前缀标识+卖家id",value:"可售商品"
  58.             Map<String, RedisSortedSetCache> sortedSetSourceMap = diffAvailableCache(sellerSaleProductMap, sellerGroupList);
  59.             //9.刷新缓存信息
  60.             redisReadWriteManager.flushIncrSortedSetMap(sortedSetSourceMap);
  61.             pageNo++;
  62.             sellerGroupList = querySellerGroupList(pageNo, request.getSellerGroupType());
  63.         }
  64.         //10.将卖家类型可售商品缓存起来 缓存结构 key:"前缀标识+卖家类型",value:"可售商品",逻辑与卖家可售商品缓存一致
  65.         //这里需要将分页查询的卖家组的可售商品合并起来,最后做已经存在的缓存diff处理
  66.         Map<String, RedisSortedSetCache> sortedSetSourceMap = diffSellerTypeAvailableCache(sellerTypeSkuIdMap);
  67.         //11.刷新缓存信息
  68.         redisReadWriteManager.flushIncrSortedSetMap(sortedSetSourceMap);
  69.         return Boolean.TRUE;
  70.     }
  71.     ...
  72. }
复制代码
 
5.商品中心架构梳理
  1. 商品M端系统:eshop-construction-service
  2. 商品C端系统:eshop-diplomacy-service
  3. 商品生命周期系统:eshop-lifecycle-service
  4. 商品调度系统:eshop-scheduling-service(定时调度可采可补可售任务)
  5. 商品补货系统:eshop-replenished-service(处理商品可采可补可售)
  6. 商品卖家系统:eshop-seller-service
复制代码
7.png
 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册