楼层: 首页/ 软件技术/ Spring Cloud 微服务/ 小项目实战:电商微服务三件套
十一

小项目实战:电商微服务三件套

Mini E-Commerce with Nacos + Gateway + Feign + Sentinel

把前面学的串起来,搭一个最小可跑的电商:user-service(用户)+ order-service(订单)+ product-service(商品)+ api-gateway(网关)+ Nacos(注册配置)+ Sentinel(熔断)。下单时订单服务通过 Feign 调用户服务查用户、调商品服务查库存,任意一个挂了走降级。

论项目结构长这样

e-commerce/(父工程)
├── e-commerce-common/(公共 DTO、工具类)
├── api-gateway/(端口 9000,统一入口)
├── user-service/(端口 8081,提供用户查询)
├── product-service/(端口 8082,提供商品库存)
└── order-service/(端口 8083,下单时调 user 和 product)

所有服务都注册到同一个 Nacos。前端只访问 http://localhost:9000/api/...,网关按路径转发。

搭项目:pom 与 application.yml 速查

每个业务服务的 pom 都差不多:Nacos 发现 + OpenFeign + Sentinel + Web。下面贴一个 order-service 的关键依赖,其他服务照着改服务名就行。

order-service/pom.xml 关键依赖

<dependencies> <!-- Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Nacos 注册发现 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!-- OpenFeign 调别人 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- Sentinel 熔断 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> </dependencies>

order-service/application.yml

server: port: 8083 spring: application: name: order-service cloud: nacos: discovery: server-addr: localhost:8848 sentinel: transport: dashboard: localhost:8080 feign: sentinel: enabled: true

order-service 的下单接口:Feign 调用户和商品,加 Sentinel 降级

@RestController @RequestMapping("/order") public class OrderController { @Autowired private UserClient userClient; // Feign 调 user-service @Autowired private ProductClient productClient; // Feign 调 product-service @GetMapping("/buy") @SentinelResource(value = "buy", fallback = "buyFallback") public String buy(Long userId, Long productId, Integer count) { // 1. 查用户 UserDTO user = userClient.getUserById(userId); // 2. 查商品库存 ProductDTO product = productClient.getProductById(productId); if (product.getStock() < count) { return "库存不足"; } return "下单成功:" + user.getName() + " 购买 " + product.getName() + " x" + count; } // 降级方法:用户服务或商品服务挂了,返回这句 public String buyFallback(Long userId, Long productId, Integer count) { return "系统繁忙,请稍后再试(降级返回)"; } }

启动顺序(重要)

# 1. 先起 Nacos(注册+配置中心) # 2. 再起 Sentinel 控制台(可选,看规则用) # 3. 起 user-service、product-service、order-service # 4. 最后起 api-gateway # 5. 浏览器访问 http://localhost:9000/api/order/buy?userId=1&productId=1&count=1 # 验证熔断:把 user-service 停掉,再访问上面的 URL # 看到 "系统繁忙,请稍后再试" 就说明降级生效了
记
实战心法

① 别一上来就 Seata、SkyWalking 全家桶,先把 Nacos + Gateway + Feign 三个跑通。

② 每个组件都问自己"它解决什么问题",答不上来就先别用。

③ 版本号是第一生产力,启动报错先查版本对应表。