SpringCloud 微服务解决方案:企业级架构实战
SpringCloud 是构建分布式微服务系统的首选框架,提供了一整套开箱即用的解决方案。
核心组件架构
┌─────────────────────────────────────────────────────┐
│ API Gateway │
│ (Spring Cloud Gateway) │
├─────────────────────────────────────────────────────┤
│ 服务发现与注册 (Nacos / Eureka / Consul) │
├───────────┬───────────┬───────────┬─────────────────┤
│ 用户服务 │ 订单服务 │ 商品服务 │ 支付服务 │
├───────────┴───────────┴───────────┴─────────────────┤
│ 配置中心 (Nacos Config) │
├─────────────────────────────────────────────────────┤
│ 消息队列 (RocketMQ / RabbitMQ) │
└─────────────────────────────────────────────────────┘
服务注册与发现
Nacos 配置
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: dev
config:
server-addr: localhost:8848
file-extension: yaml
服务注册示例
@SpringBootApplication
@EnableDiscoveryClient
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
服务间调用
OpenFeign 声明式调用
@FeignClient(name = "product-service", fallback = ProductFallback.class)
public interface ProductClient {
@GetMapping("/api/products/{id}")
Product getProductById(@PathVariable("id") Long id);
@PostMapping("/api/products/batch")
List<Product> getProductsByIds(@RequestBody List<Long> ids);
}
负载均衡配置
spring:
cloud:
loadbalancer:
ribbon:
enabled: false
nacos:
enabled: true
网关配置
Spring Cloud Gateway 路由
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 100
redis-rate-limiter.burstCapacity: 200
熔断与限流
Sentinel 配置
@SentinelResource(value = "getOrder",
blockHandler = "handleBlock",
fallback = "handleFallback")
public Order getOrder(Long orderId) {
return orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException(orderId));
}
public Order handleBlock(Long orderId, BlockException ex) {
log.warn("请求被限流: orderId={}", orderId);
return Order.empty();
}
public Order handleFallback(Long orderId, Throwable ex) {
log.error("服务降级: orderId={}, error={}", orderId, ex.getMessage());
return Order.defaultOrder();
}
分布式事务
Seata AT 模式
@GlobalTransactional(rollbackFor = Exception.class)
public void createOrder(OrderDTO orderDTO) {
// 1. 扣减库存
productService.deductStock(orderDTO.getProductId(), orderDTO.getQuantity());
// 2. 扣减余额
accountService.deductBalance(orderDTO.getUserId(), orderDTO.getAmount());
// 3. 创建订单
orderRepository.save(orderDTO.toEntity());
}
链路追踪
Sleuth + Zipkin
spring:
sleuth:
sampler:
probability: 1.0
zipkin:
base-url: http://localhost:9411
sender:
type: web
核心组件对比
| 功能 | 推荐方案 | 备选方案 |
|---|---|---|
| 注册中心 | Nacos | Eureka, Consul |
| 配置中心 | Nacos Config | Apollo, Spring Cloud Config |
| 网关 | Spring Cloud Gateway | Zuul, Kong |
| 熔断限流 | Sentinel | Hystrix, Resilience4j |
| 负载均衡 | Spring Cloud LoadBalancer | Ribbon |
| 分布式事务 | Seata | TCC, 消息最终一致性 |
总结
SpringCloud 微服务架构需要根据业务规模选择合适的组件组合,建议从 Nacos + Gateway + OpenFeign + Sentinel 起步,逐步完善分布式事务和链路追踪能力。