Skip to content

Spring Cloud 微服务

微服务架构

┌─────────────────────────────────────────────────────────────────┐
│                      微服务架构                                    │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   ┌─────────┐   ┌─────────┐   ┌─────────┐                       │
│   │ Gateway │──▶│Service A│──▶│Service B│                       │
│   └─────────┘   └─────────┘   └─────────┘                       │
│        │              │              │                          │
│        ▼              ▼              ▼                          │
│   ┌─────────┐   ┌─────────┐   ┌─────────┐                       │
│   │  Config │   │ Registry│   │  Monitor│                       │
│   │ Server  │   │ Center   │   │         │                       │
│   └─────────┘   └─────────┘   └─────────┘                       │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

核心组件

组件作用常用实现
服务网关请求路由、认证Gateway, Zuul
服务注册与发现动态服务管理Nacos, Eureka
配置中心集中配置管理Nacos Config, Spring Cloud Config
负载均衡流量分发Ribbon, LoadBalancer
服务调用HTTP 调用OpenFeign
熔断器故障隔离Sentinel, Hystrix
分布式事务跨服务一致性Seata

Nacos - 服务注册与配置中心

快速开始

yaml
# 引入依赖
<!-- nacos-discovery -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

# application.yml
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
        namespace: dev
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yaml
  application:
    name: user-service

Nacos 作为配置中心

java
// 动态配置
@RestController
@RefreshScope  // 自动刷新配置
public class ConfigController {

    @Value("${app.message:默认消息}")
    private String message;

    @GetMapping("/message")
    public String getMessage() {
        return message;
    }
}

Gateway - API 网关

工作原理

┌─────────────────────────────────────────────────────────────────┐
│                      Gateway 请求处理流程                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   请求 ──▶ Route Predicate ──▶ Filter Chain ──▶ 后端服务        │
│                                                                  │
│   常用 Predicate:                                                │
│   - Path=/api/**                                                │
│   - Method=GET,POST                                             │
│   - Header=X-Request-Id, \\d+                                   │
│   - Query=name,张三                                              │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

配置示例

yaml
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service  # lb = loadbalance
          predicates:
            - Path=/user/**
          filters:
            - StripPrefix=1  # 去掉第一层路径

        - id: order-service
          uri: lb://order-service
          predicates:
            - Path=/order/**

      # 全局过滤器
      default-filters:
        - DedupeResponseHeader=Vary Access-Control-Allow-Credentials

动态路由

java
@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("user_route", r -> r.path("/api/user/**")
                .filters(f -> f.stripPrefix(1))
                .uri("lb://user-service"))
            .build();
    }
}

OpenFeign - 服务调用

快速开始

java
// 1. 引入依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

// 2. 启用 Feign
@SpringCloudApplication
@EnableFeignClients
public class OrderApplication { }

// 3. 定义接口
@FeignClient(name = "user-service", url = "${user.service.url:http://localhost:8080}")
public interface UserClient {

    @GetMapping("/user/{id}")
    User getUser(@PathVariable("id") Long id);

    @PostMapping("/user")
    User createUser(@RequestBody User user);
}

// 4. 使用
@Service
public class OrderService {

    @Autowired
    private UserClient userClient;

    public Order createOrder(Long userId) {
        User user = userClient.getUser(userId);
        // 创建订单逻辑
    }
}

高级配置

java
// 自定义配置
@Configuration
public class FeignConfig {

    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

@FeignClient(name = "user-service", configuration = FeignConfig.class)
public interface UserClient { }

Sentinel - 熔断器

限流规则

java
// 1. 引入依赖
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

// 2. 定义资源
@RestController
public class UserController {

    @GetMapping("/user/{id}")
    @SentinelResource(value = "getUser",
        blockHandler = "getUserBlockHandler",
        fallback = "getUserFallback")
    public User getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }

    // 限流处理
    public User getUserBlockHandler(Long id, BlockException ex) {
        return User.builder().name("系统繁忙").build();
    }

    // 降级处理
    public User getUserFallback(Long id, Throwable ex) {
        return User.builder().name("服务不可用").build();
    }
}

配置限流规则

yaml
spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-sentinel
            groupId: DEFAULT_GROUP
            ruleType: flow

Seata - 分布式事务

AT 模式

java
// 1. 引入依赖
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>

// 2. 配置
# application.yml
seata:
  tx-service-group: my_test_tx_group
  registry:
    type: nacos
    nacos:
      server-addr: 127.0.0.1:8848

// 3. 使用 @GlobalTransactional
@GlobalTransactional(rollbackFor = Exception.class)
public void createOrder(OrderDTO orderDTO) {
    // 1. 创建订单
    orderService.createOrder(orderDTO);

    // 2. 扣减库存(远程调用)
    storageClient.deduct(orderDTO.getProductId(), orderDTO.getCount());

    // 3. 扣减余额(远程调用)
    accountClient.deduct(orderDTO.getUserId(), orderDTO.getAmount());

    // 任意一步失败,全局回滚
}

Spring Cloud Alibaba

常用组件

组件作用替代方案
Sentinel流控、降级、熔断Hystrix
Nacos注册中心、配置中心Eureka + Config
Seata分布式事务-
DubboRPC 调用OpenFeign

完整依赖

xml
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2022.0.0.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <!-- Nacos -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

    <!-- Sentinel -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>

    <!-- OpenFeign -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>

    <!-- Seata -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
    </dependency>
</dependencies>

总结

Spring Cloud 核心知识点

知识点面试频率实战重要性
Nacos 注册/配置中心⭐⭐⭐⭐⭐⭐⭐⭐⭐
Gateway 路由⭐⭐⭐⭐⭐⭐⭐⭐⭐
OpenFeign 服务调用⭐⭐⭐⭐⭐⭐⭐⭐⭐
Sentinel 熔断限流⭐⭐⭐⭐⭐⭐⭐⭐
Seata 分布式事务⭐⭐⭐⭐⭐⭐⭐⭐

⚠️ 易错点提醒

  1. Gateway 的 Predicate 执行顺序很重要
  2. OpenFeign 需要配合熔断器使用(如 Sentinel)
  3. Seata AT 模式依赖 undo_log 表
  4. Nacos 配置变更需要 @RefreshScope 才能生效
  5. 分布式事务尽量避免,非必要不使用