当前位置:网站首页 >  教程

商城分销系统从0到1:手把手搭建可裂变的技术架构

时间:2026年05月31日 18:40:30 来源:易频IT社区

一、核心架构设计

商城分销系统的核心在于实现用户关系链追踪与佣金计算。我们采用三级分销模型,这是最常用且合规的模型。整个系统由以下几个核心模块组成:

  • 用户关系树:记录用户的上下级关系。
  • 分销员体系:管理分销员的申请、审核与等级。
  • 订单追踪:将订单与推荐关系绑定。
  • 佣金计算引擎:根据规则实时或定期计算佣金。
  • 佣金账户与提现:管理资金流。

技术栈选择:后端使用Spring Boot,数据库使用MySQL,缓存使用Redis。确保你已安装JDK 8+、Maven 3.6+、MySQL 5.7+和Redis 5.0+。

二、数据库设计与建表

首先创建数据库。以下SQL脚本包含最精简但功能完整的核心表结构。

1. 创建数据库与核心表

登录MySQL,执行以下命令:

``` CREATE DATABASE IF NOT EXISTS `mall_distribute` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; USE `mall_distribute`; ```

接着创建用户关系表,这是整个系统的基石。

``` CREATE TABLE `user_relation` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) NOT NULL COMMENT '用户ID', `parent_id` bigint(20) DEFAULT NULL COMMENT '直接上级ID', `root_id` bigint(20) DEFAULT NULL COMMENT '根节点ID(团队最顶端)', `level` tinyint(4) NOT NULL DEFAULT '1' COMMENT '层级(从1开始)', `invite_code` varchar(20) NOT NULL COMMENT '用户的唯一邀请码', `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `uk_user_id` (`user_id`), UNIQUE KEY `uk_invite_code` (`invite_code`), KEY `idx_parent_id` (`parent_id`), KEY `idx_root_id` (`root_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户关系表'; ```

创建分销员信息表。

``` CREATE TABLE `distributor` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) NOT NULL, `level` tinyint(4) NOT NULL DEFAULT '1' COMMENT '分销等级,对应不同佣金比例', `status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '状态:0-审核中,1-正常,2-禁用', `total_commission` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '累计获得佣金', `available_commission` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '可提现佣金', `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `uk_user_id` (`user_id`), KEY `idx_status` (`status`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='分销员表'; ```

创建佣金规则表,用于灵活配置不同等级的分佣比例。

``` CREATE TABLE `commission_rule` ( `id` int(11) NOT NULL AUTO_INCREMENT, `distributor_level` tinyint(4) NOT NULL COMMENT '分销员等级', `product_category_id` int(11) DEFAULT NULL COMMENT '商品类目ID,NULL表示全局规则', `commission_type` tinyint(4) NOT NULL COMMENT '1-比例,2-固定金额', `value` decimal(5,2) NOT NULL COMMENT '比例值或固定金额', `target_level` tinyint(4) NOT NULL COMMENT '针对哪一级上级(1-直接上级,2-间上级,3-间上上级)', `is_active` tinyint(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`), KEY `idx_level_category` (`distributor_level`,`product_category_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='佣金规则表'; ```

商城分销系统从0到1:手把手搭建可裂变的技术架构

创建订单分佣记录表,这是财务对账的核心。

``` CREATE TABLE `order_commission` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `order_id` varchar(32) NOT NULL COMMENT '订单号', `order_amount` decimal(10,2) NOT NULL COMMENT '订单实际支付金额', `buyer_id` bigint(20) NOT NULL COMMENT '购买者ID', `distributor_id` bigint(20) NOT NULL COMMENT '获得佣金的分销员ID', `rule_id` int(11) NOT NULL COMMENT '所使用的佣金规则ID', `commission_amount` decimal(10,2) NOT NULL COMMENT '计算出的佣金金额', `settle_status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '结算状态:0-未结算,1-已结算', `created_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `settled_time` datetime DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uk_order_distributor` (`order_id`,`distributor_id`), KEY `idx_distributor_settle` (`distributor_id`,`settle_status`), KEY `idx_created_time` (`created_time`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单佣金记录表'; ```

三、Spring Boot后端核心实现

创建Spring Boot项目,在pom.xml中确保引入以下依赖。

``` org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-data-redis ```

1. 用户关系绑定逻辑

这是分销的起点。在用户注册时,需要处理邀请码。创建UserRelationService.java。

``` @Service public class UserRelationService { @Autowired private UserRelationRepository userRelationRepo; @Autowired private RedisTemplate redisTemplate; // 生成唯一邀请码(示例:6位数字字母混合) private String generateInviteCode(Long userId) { // 简单示例:Base62编码用户ID,并确保唯一性 String code = Base62.encode(userId); // 实际中需检查唯一性,这里省略 return code; } @Transactional public void bindRelation(Long userId, String inviteCode) { // 1. 查找邀请人 UserRelation inviter = userRelationRepo.findByInviteCode(inviteCode); if (inviter == null) { throw new RuntimeException("邀请码无效"); } // 2. 创建新用户的关系记录 UserRelation newUserRelation = new UserRelation(); newUserRelation.setUserId(userId); newUserRelation.setParentId(inviter.getUserId()); newUserRelation.setInviteCode(generateInviteCode(userId)); newUserRelation.setLevel(inviter.getLevel() + 1); // 3. 设置根节点:如果邀请人自己就是根,则根为邀请人;否则继承邀请人的根 if (inviter.getRootId() == null) { newUserRelation.setRootId(inviter.getUserId()); } else { newUserRelation.setRootId(inviter.getRootId()); } userRelationRepo.save(newUserRelation); // 4. 将用户关系路径存入Redis,方便快速查询(例如:user:relation:1001 -> 1000,999) String key = "user:relation:path:" + userId; // 获取邀请人的完整路径 String parentPath = redisTemplate.opsForValue().get("user:relation:path:" + inviter.getUserId()); String currentPath = (parentPath == null ? String.valueOf(inviter.getUserId()) : parentPath + "," + inviter.getUserId()); redisTemplate.opsForValue().set(key, currentPath); } } ```

2. 佣金计算引擎

当订单支付成功后,调用此服务计算佣金。创建CommissionService.java。

``` @Service public class CommissionService { @Autowired private OrderCommissionRepository orderCommissionRepo; @Autowired private DistributorRepository distributorRepo; @Autowired private CommissionRuleRepository ruleRepo; @Autowired private UserRelationRepository userRelationRepo; @Transactional public void calculateCommission(String orderId, Long buyerId, BigDecimal orderAmount, Integer productCategoryId) { // 1. 获取购买者的关系路径 UserRelation buyerRelation = userRelationRepo.findByUserId(buyerId); if (buyerRelation == null || buyerRelation.getParentId() == null) { return; // 无上级,不分佣 } // 2. 获取三级上级(根据需求调整) List parentIds = getUpperLevelUserIds(buyerId, 3); // 3. 为每一个有效的上级分销员计算佣金 for (int i = 0; i < parentIds.size(); i++) { Long distributorUserId = parentIds.get(i); Distributor distributor = distributorRepo.findByUserIdAndStatus(distributorUserId, 1); // 状态正常的分销员 if (distributor == null) { continue; } // 4. 查找匹配的佣金规则:优先商品类目规则,找不到则用全局规则 CommissionRule rule = ruleRepo.findByDistributorLevelAndProductCategoryId(distributor.getLevel(), productCategoryId); if (rule == null) { rule = ruleRepo.findByDistributorLevelAndProductCategoryIdIsNull(distributor.getLevel()); } if (rule == null || rule.getIsActive() == 0) { continue; } // 5. 计算佣金金额 BigDecimal commissionAmount; if (rule.getCommissionType() == 1) { // 比例 commissionAmount = orderAmount.multiply(rule.getValue().divide(new BigDecimal("100"))); } else { // 固定金额 commissionAmount = rule.getValue(); } // 6. 保存佣金记录 OrderCommission record = new OrderCommission(); record.setOrderId(orderId); record.setOrderAmount(orderAmount); record.setBuyerId(buyerId); record.setDistributorId(distributor.getId()); record.setRuleId(rule.getId()); record.setCommissionAmount(commissionAmount); record.setSettleStatus(0); orderCommissionRepo.save(record); // 7. 实时更新分销员的可提现佣金(也可采用定时任务批量更新) distributor.setAvailableCommission(distributor.getAvailableCommission().add(commissionAmount)); distributor.setTotalCommission(distributor.getTotalCommission().add(commissionAmount)); distributorRepo.save(distributor); } } // 工具方法:获取指定层级的上线用户ID列表 private List getUpperLevelUserIds(Long userId, int maxLevel) { List result = new ArrayList<>(); Long currentUserId = userId; for (int i = 0; i < maxLevel; i++) { UserRelation relation = userRelationRepo.findByUserId(currentUserId); if (relation == null || relation.getParentId() == null) { break; } result.add(relation.getParentId()); currentUserId = relation.getParentId(); } return result; } } ```

四、关键配置与部署

1. application.yml 数据库与Redis配置

在src/main/resources/application.yml中配置。

``` spring: datasource: url: jdbc:mysql://localhost:3306/mall_distribute?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: your_password driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate: dialect: org.hibernate.dialect.MySQL8Dialect redis: host: localhost port: 6379 password: database: 0 timeout: 2000ms ```

2. 初始化佣金规则

系统启动后,必须初始化基础佣金规则。在数据库执行以下SQL,或通过管理后台添加。

``` INSERT INTO `commission_rule` (`distributor_level`, `product_category_id`, `commission_type`, `value`, `target_level`) VALUES (1, NULL, 1, '10.00', 1), -- 1级分销员,全局规则,佣金比例10%,给直接上级 (1, NULL, 1, '5.00', 2), -- 1级分销员,全局规则,佣金比例5%,给间上级 (1, NULL, 1, '2.00', 3), -- 1级分销员,全局规则,佣金比例2%,给间上上级 (2, NULL, 1, '12.00', 1), -- 2级分销员,比例更高 (2, NULL, 1, '6.00', 2), (2, NULL, 1, '3.00', 3); ```

3. 核心接口暴露

创建DistributeController.java,提供关键API。

``` @RestController @RequestMapping("/api/distribute") public class DistributeController { @Autowired private UserRelationService userRelationService; @Autowired private CommissionService commissionService; // 用户注册时绑定邀请关系 @PostMapping("/bind") public Result bindInviter(@RequestParam Long userId, @RequestParam String inviteCode) { userRelationService.bindRelation(userId, inviteCode); return Result.success(); } // 模拟订单支付成功回调,触发分佣计算 @PostMapping("/order/pay") public Result orderPaySuccess(@RequestParam String orderId, @RequestParam Long buyerId, @RequestParam BigDecimal amount, @RequestParam Integer categoryId) { commissionService.calculateCommission(orderId, buyerId, amount, categoryId); return Result.success(); } // 分销员查看我的佣金概况 @GetMapping("/commission/summary") public Result getCommissionSummary(@RequestParam Long distributorId) { // 查询逻辑... return Result.success(data); } } ```

五、上线前检查清单

  • 数据库索引:确保user_relation表的parent_id、root_id,order_commission表的distributor_id、order_id字段已添加索引。
  • 事务一致性:确保bindRelation和calculateCommission方法上的@Transactional生效,数据库引擎为InnoDB。
  • 并发处理:在高并发下,生成唯一邀请码、更新分销员佣金时,考虑使用数据库乐观锁或分布式锁。
  • 数据安全:佣金计算金额使用Decimal类型,避免浮点数精度丢失。所有金额字段精确到分(两位小数)。
  • 日志记录:在佣金计算的关键步骤(如规则匹配、金额计算)添加详细日志,便于后续对账和排查问题。
  • 监控报警:监控订单分佣的失败率,设置报警阈值。监控Redis内存使用情况。

按照以上步骤,你已经搭建了一个具备核心功能、可直接运行的分销系统后端。前端只需调用提供的API即可完成关系绑定、佣金展示和提现流程。

标签 商城分销

相关推荐

最新

热门

推荐

精选

标签

易频IT社区是综合性互联网IT技术门户网站,专注分享网络技术、服务器运维、网络安全、编程开发、系统架构、云计算、大数据等行业干货,实时更新IT行业资讯、零基础教程、实战案例,为IT从业者、技术爱好者提供专业的学习交流平台。

Copyright © 2021-2026 易频IT社区. All Rights Reserved. 备案号:闽ICP备2023013482号 网站地图