SpringCloud 微服務(wù)解決方案:企業(yè)級架構(gòu)實戰(zhàn)
SpringCloud 是構(gòu)建分布式微服務(wù)系統(tǒng)的首選框架,提供了一整套開箱即用的解決方案。
核心組件架構(gòu)
┌─────────────────────────────────────────────────────┐
│ API Gateway │
│ (Spring Cloud Gateway) │
├─────────────────────────────────────────────────────┤
│ 服務(wù)發(fā)現(xiàn)與注冊 (Nacos / Eureka / Consul) │
├───────────┬───────────┬───────────┬─────────────────┤
│ 用戶服務(wù) │ 訂單服務(wù) │ 商品服務(wù) │ 支付服務(wù) │
├───────────┴───────────┴───────────┴─────────────────┤
│ 配置中心 (Nacos Config) │
├─────────────────────────────────────────────────────┤
│ 消息隊列 (RocketMQ / RabbitMQ) │
└─────────────────────────────────────────────────────┘
服務(wù)注冊與發(fā)現(xiàn)
Nacos 配置
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
namespace: dev
config:
server-addr: localhost:8848
file-extension: yaml
服務(wù)注冊示例
@SpringBootApplication
@EnableDiscoveryClient
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
服務(wù)間調(diào)用
OpenFeign 聲明式調(diào)用
@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);
}
負(fù)載均衡配置
spring:
cloud:
loadbalancer:
ribbon:
enabled: false
nacos:
enabled: true
網(wǎng)關(guān)配置
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("服務(wù)降級: orderId={}, error={}", orderId, ex.getMessage());
return Order.defaultOrder();
}
分布式事務(wù)
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. 創(chuàng)建訂單
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 |
| 網(wǎng)關(guān) | Spring Cloud Gateway | Zuul, Kong |
| 熔斷限流 | Sentinel | Hystrix, Resilience4j |
| 負(fù)載均衡 | Spring Cloud LoadBalancer | Ribbon |
| 分布式事務(wù) | Seata | TCC, 消息最終一致性 |
總結(jié)
SpringCloud 微服務(wù)架構(gòu)需要根據(jù)業(yè)務(wù)規(guī)模選擇合適的組件組合,建議從 Nacos + Gateway + OpenFeign + Sentinel 起步,逐步完善分布式事務(wù)和鏈路追蹤能力。