【微服务初体验】Spring Cloud+MySQL构建简易电商系统

技术选型与架构设计

Spring Cloud 微服务架构通常包含以下核心组件:

  • 服务注册与发现:Eureka/Nacos
  • API网关:Spring Cloud Gateway
  • 配置中心:Spring Cloud Config/Nacos
  • 数据库:MySQL 8.0+分库分表
  • 服务间通信:OpenFeign/RestTemplate
  • 熔断降级:Hystrix/Sentinel

典型服务拆分示例:

  • 用户服务(user-service)
  • 商品服务(product-service)
  • 订单服务(order-service)
  • 支付服务(payment-service)

数据库设计要点

MySQL表结构设计应遵循微服务边界:

sql 复制代码
CREATE TABLE `product` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `stock` int DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `order` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `user_id` bigint NOT NULL,
  `total_amount` decimal(10,2) NOT NULL,
  `status` tinyint DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

分库分表策略建议:

  • 用户ID取模分片
  • 时间范围分表
  • 使用ShardingSphere实现

服务实现示例

商品服务接口定义:

java 复制代码
@RestController
@RequestMapping("/products")
public class ProductController {
    
    @Autowired
    private ProductService productService;

    @GetMapping("/{id}")
    public Product getProduct(@PathVariable Long id) {
        return productService.getById(id);
    }

    @PostMapping("/reduce-stock")
    public Boolean reduceStock(@RequestParam Long productId, 
                             @RequestParam Integer quantity) {
        return productService.reduceStock(productId, quantity);
    }
}

Feign客户端调用示例:

java 复制代码
@FeignClient(name = "product-service", path = "/products")
public interface ProductFeignClient {
    
    @GetMapping("/{id}")
    Product getProduct(@PathVariable Long id);

    @PostMapping("/reduce-stock")
    Boolean reduceStock(@RequestParam Long productId, 
                      @RequestParam Integer quantity);
}

分布式事务处理

Seata AT模式配置:

properties 复制代码
# application.properties
spring.cloud.alibaba.seata.tx-service-group=my_test_tx_group
seata.service.grouplist.default=127.0.0.1:8091

业务方法注解:

java 复制代码
@GlobalTransactional
public void createOrder(OrderDTO orderDTO) {
    // 1. 扣减库存
    productFeignClient.reduceStock(orderDTO.getProductId(), orderDTO.getQuantity());
    
    // 2. 创建订单
    orderService.create(orderDTO);
    
    // 3. 扣减余额
    accountFeignClient.decrease(orderDTO.getUserId(), orderDTO.getAmount());
}

性能优化建议

缓存策略实施:

java 复制代码
@Cacheable(value = "product", key = "#id")
public Product getById(Long id) {
    return productMapper.selectById(id);
}

@CacheEvict(value = "product", key = "#productId")
public Boolean reduceStock(Long productId, Integer quantity) {
    return productMapper.reduceStock(productId, quantity) > 0;
}

接口限流配置:

java 复制代码
@RestController
@SentinelResource(value = "productApi", 
                blockHandler = "handleBlock")
public class ProductController {
    
    public Product handleBlock(Long id, BlockException ex) {
        return Product.emptyProduct();
    }
}

部署与监控

Docker Compose部署示例:

yaml 复制代码
version: '3'
services:
  product-service:
    image: demo/product-service:1.0
    ports:
      - "8081:8080"
    depends_on:
      - mysql
      - nacos

  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: root

监控指标采集:

XML 复制代码
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
相关推荐
回家路上绕了弯5 小时前
海量日志分析:一天内最大在线人数与最长持续时间计算方案
后端·微服务
蒲公英源码5 小时前
uniapp开源ERP多仓库管理系统
mysql·elementui·uni-app·php
小码过河.5 小时前
告别 mysqldump 痛点!用 mydumper 实现 MySQL 高效备份与恢复
数据库·mysql
是2的10次方啊6 小时前
MySQL索引优化实战:原则速查与踩坑案例(实战篇)
mysql
Hello.Reader9 小时前
基于 Flink CDC 的 MySQL → Kafka Streaming ELT 实战
mysql·flink·kafka
L.EscaRC10 小时前
浅析MySQL InnoDB存储引擎的MVCC实现原理
数据库·mysql
-指短琴长-17 小时前
MySQL快速入门——基本查询(下)
android·mysql·adb
August_._18 小时前
【MySQL】SQL语法详细总结
java·数据库·后端·sql·mysql·oracle
林北北的霸霸21 小时前
django初识与安装
android·mysql·adb
A.说学逗唱的Coke21 小时前
【观察者模式】深入 Spring 事件驱动模型:从入门到微服务整合实战
spring·观察者模式·微服务