Spring Cloud 基础概念
Spring Cloud 是一套基于 Spring Boot 的微服务开发工具集,用于快速构建分布式系统中的常见模式(如配置管理、服务发现、断路器、智能路由等)。其核心目标是简化分布式系统的开发。
核心组件与功能
服务发现与注册(Eureka/Nacos)
- Eureka:Netflix 开源的服务注册与发现组件,包含 Eureka Server(注册中心)和 Eureka Client(服务客户端)。
- Nacos:阿里开源的动态服务发现与配置管理平台,支持更丰富的功能如配置中心、命名服务等。
配置中心(Spring Cloud Config/Nacos)
- 通过集中式配置管理,动态更新应用配置,支持 Git、数据库等存储方式。
- Nacos 同时提供配置管理功能,可替代 Spring Cloud Config。
负载均衡(Ribbon/Spring Cloud LoadBalancer)
- Ribbon:客户端负载均衡工具,支持轮询、随机等策略。
- Spring Cloud LoadBalancer:Spring 官方提供的轻量级替代方案。
服务调用(OpenFeign)
- 声明式的 REST 客户端,通过接口注解简化 HTTP 请求的编写。
断路器(Hystrix/Sentinel)
- Hystrix:Netflix 开源的容错库,提供熔断、降级、隔离等功能。
- Sentinel:阿里开源的流量控制与熔断降级组件,支持实时监控。
网关(Spring Cloud Gateway)
- 替代 Zuul 的 API 网关,基于 Reactor 实现异步非阻塞模型,支持路由、过滤、限流等功能。
快速入门示例
1. 创建 Eureka Server
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
配置 application.yml
:
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
2. 创建服务提供者(Eureka Client)
@SpringBootApplication
@EnableEurekaClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
配置 application.yml
:
server:
port: 8081
spring:
application:
name: service-provider
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
3. 使用 OpenFeign 调用服务
添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
定义 Feign 接口:
@FeignClient(name = "service-provider")
public interface ProviderClient {
@GetMapping("/hello")
String hello();
}
启动类添加 @EnableFeignClients
注解。
常见问题与解决方案
服务注册失败
- 检查 Eureka Server 地址是否正确,确保网络连通。
- 验证
spring.application.name
是否唯一。
配置中心动态刷新失效
- 添加
@RefreshScope
注解到需要刷新的 Bean。 - 通过
POST /actuator/refresh
手动触发刷新。
熔断器不生效
- 确认 Hystrix/Sentinel 依赖已引入。
- 检查
@EnableCircuitBreaker
或@EnableHystrix
是否启用。
进阶学习资源
- 官方文档:Spring Cloud Reference
- 书籍:《Spring Cloud Alibaba 微服务原理与实战》
- 实战项目:Spring Cloud 微服务案例