标签:Spring Cloud Alibaba、微服务、Nacos、Sentinel、Seata

一、为什么需要 Spring Cloud Alibaba?

在传统的单体应用中,所有功能模块都打包在一个应用里。随着业务增长,系统变得臃肿、难以维护和扩展。微服务架构应运而生——将一个大系统拆分成多个独立部署、职责单一的小服务。

但微服务也带来了新挑战:

  • 服务如何注册与发现?
  • 配置如何统一管理?
  • 如何防止服务雪崩?
  • 分布式事务怎么处理?

Spring Cloud Alibaba(SCA) 就是为解决这些问题而生的一站式微服务解决方案,它整合了阿里巴巴多年高并发、高可用系统的实践经验,并与 Spring Cloud 生态无缝集成。


二、Spring Cloud Alibaba 核心组件概览

组件功能对标 Spring Cloud
Nacos服务注册中心 + 配置中心Eureka + Config
Sentinel流量控制、熔断降级Hystrix
Seata分布式事务解决方案——
RocketMQ消息队列(可选)RabbitMQ/Kafka
DubboRPC 框架(可选)Feign/RestTemplate

✅ 本文重点讲解 Nacos + Sentinel 的基础使用。


三、需求场景:用户下单系统

假设我们要开发一个简单的电商系统,包含两个服务:

  • user-service:提供用户信息查询
  • order-service:创建订单,需调用 user-service 获取用户信息

要求:

  1. 服务能自动注册与发现
  2. 订单服务调用用户服务时,若用户服务宕机,不能导致整个系统崩溃(熔断)
  3. 配置能动态刷新(如超时时间)

四、环境准备

  • JDK 17+
  • Maven 3.8+
  • Spring Boot 3.2.x(注意:Spring Cloud Alibaba 2022.x 支持 Spring Boot 3)
  • Nacos Server(下载地址:https://github.com/alibaba/nacos/releases)

启动 Nacos(单机模式):

# Linux/Mac
sh startup.sh -m standalone

# Windows
startup.cmd -m standalone

访问 http://localhost:8848/nacos,默认账号密码:nacos/nacos


五、实战:搭建 user-service(服务提供者)

1. 创建 Spring Boot 项目

pom.xml 关键依赖:

<properties>
    <spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version>
    <spring-cloud.version>2022.0.4</spring-cloud.version>
</properties>

<dependencies>
    <!-- Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

    <!-- Actuator(用于健康检查)-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${spring-cloud-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2. 配置文件 application.yml

server:
  port: 8081

spring:
  application:
    name: user-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

management:
  endpoints:
    web:
      exposure:
        include: '*'

3. 编写 Controller

@RestController
public class UserController {

    @GetMapping("/user/{id}")
    public Map<String, Object> getUser(@PathVariable Long id) {
        return Map.of("id", id, "name", "张三", "email", "zhangsan@example.com");
    }
}

4. 启动类

@SpringBootApplication
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}

✅ 启动后,访问 Nacos 控制台,能看到 user-service 已注册。


六、实战:搭建 order-service(服务消费者 + 熔断)

1. 添加依赖(额外加入 Sentinel)

<!-- 除 user-service 的依赖外,增加 -->
<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>

2. 配置文件 application.yml

server:
  port: 8082

spring:
  application:
    name: order-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080  # Sentinel 控制台地址(需单独启动)
        port: 8719

# Feign 开启 Sentinel 支持
feign:
  sentinel:
    enabled: true

management:
  endpoints:
    web:
      exposure:
        include: '*'

💡 Sentinel 控制台需单独下载启动(jar 包):
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -jar sentinel-dashboard.jar

3. 声明 Feign Client(带 fallback)

@FeignClient(name = "user-service", fallback = UserClientFallback.class)
public interface UserClient {
    @GetMapping("/user/{id}")
    Map<String, Object> getUser(@PathVariable("id") Long id);
}

// 降级实现
@Component
public class UserClientFallback implements UserClient {
    @Override
    public Map<String, Object> getUser(Long id) {
        return Map.of("error", "用户服务不可用,请稍后再试");
    }
}

4. Order Controller

@RestController
public class OrderController {

    @Autowired
    private UserClient userClient;

    @GetMapping("/order/create")
    public Map<String, Object> createOrder(@RequestParam Long userId) {
        Map<String, Object> user = userClient.getUser(userId);
        return Map.of(
            "orderId", System.currentTimeMillis(),
            "userId", userId,
            "userInfo", user
        );
    }
}

5. 启动类(启用 Feign)

@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }
}

七、测试效果

  1. 启动 Nacos、user-service、order-service、Sentinel Dashboard
  2. 访问:http://localhost:8082/order/create?userId=1001
    • 正常返回用户信息 + 订单 ID
  3. 关闭 user-service
  4. 再次访问,返回:
{
  "orderId": 1732612345678,
  "userId": 1001,
  "userInfo": {
    "error": "用户服务不可用,请稍后再试"
  }
}

✅ 实现了服务熔断降级,系统未崩溃!


八、反例:不使用 SCA 的常见问题

❌ 反例1:硬编码服务地址

// 错误做法:直接写死 IP 和端口
String url = "http://192.168.1.10:8081/user/" + userId;

问题

  • 服务迁移后需改代码
  • 无法负载均衡
  • 无健康检查

❌ 反例2:无熔断机制

// 直接 RestTemplate 调用,无 fallback
ResponseEntity<User> response = restTemplate.getForEntity(url, User.class);

问题

  • user-service 宕机 → order-service 线程阻塞 → 雪崩

❌ 反例3:配置写死在代码中

int timeout = 5000; // 写死超时时间

问题

  • 修改需重新打包部署
  • 无法灰度发布配置

九、注意事项(避坑指南)

  1. 版本兼容性
    Spring Boot 3.x 必须使用 Spring Cloud 2022+ 和 SCA 2022.0.0.0+,否则启动报错。

  2. Nacos 命名空间隔离
    开发、测试、生产环境建议使用不同 namespace,避免服务互相干扰。

  3. Sentinel 规则持久化
    默认规则保存在内存,重启丢失!生产环境需对接 Nacos 或 Apollo 持久化。

  4. Feign + Sentinel 的 fallback 限制
    fallback 类必须是 @Component,且方法签名必须完全一致。

  5. 服务注册延迟
    服务启动后可能有几秒延迟才出现在 Nacos,调用前确保已注册。


十、总结

Spring Cloud Alibaba 极大简化了微服务开发:

  • Nacos:一站式服务治理 + 配置管理
  • Sentinel:实时流量防护,防雪崩利器
  • 生态兼容:无缝对接 Spring Cloud,学习成本低

🌟 小白建议:先掌握 Nacos 服务注册发现 + Feign 调用,再逐步引入 Sentinel 熔断、Seata 分布式事务

更多推荐