java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Cloud入门

Spring Cloud入门详细介绍(适合新手)

作者:廋到被风吹走

Spring Cloud是目前国内使用最广泛的微服务框架,它集成了多种微服务功能组件,并基于Spring Boot实现了自动装配,从而提供了开箱即用的良好开发体验,这篇文章主要介绍了Spring Cloud入门的相关资料,需要的朋友可以参考下

前言

Spring Cloud 是构建分布式微服务架构一站式解决方案,基于 Spring Boot 实现了一系列工具集,帮助开发者快速实现服务发现、配置管理、熔断降级、网关路由等微服务核心模式。它定位为微服务治理的"全家桶",是 Spring 生态在云原生时代的延伸。

一、核心定位与架构哲学

1. 解决的问题

在传统单体应用拆分为微服务后,面临十大核心挑战

2. 与 Spring Boot 的关系

Spring Boot          ← 基础,快速构建独立应用
    ↓
Spring Cloud         ← 增强,构建分布式系统
    ↓
Kubernetes/Service Mesh ← 基础设施层,容器编排与服务治理

核心原则

二、核心组件体系

1. 服务发现:Eureka → Nacos

Netflix Eureka(传统)

// 服务端(注册中心)
@EnableEurekaServer
@SpringBootApplication
public class EurekaServer {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServer.class, args);
    }
}

// 客户端(微服务)
@EnableEurekaClient
@SpringBootApplication
public class OrderService {
    public static void main(String[] args) {
        SpringApplication.run(OrderService.class, args);
    }
}

// application.yml
eureka:
  client:
    service-url:
      defaultZone: http://eureka1:8761/eureka,http://eureka2:8762/eureka

阿里巴巴 Nacos(现代推荐)

// Nacos 支持 AP/CP 模式切换,同时提供服务发现和配置管理
@EnableDiscoveryClient
@SpringBootApplication
public class PaymentService {
    public static void main(String[] args) {
        SpringApplication.run(PaymentService.class, args);
    }
}

// application.yml
spring:
  cloud:
    nacos:
      discovery:
        server-addr: nacos-server:8848
        namespace: production
        group: DEFAULT_GROUP
      config:
        server-addr: nacos-server:8848
        file-extension: yaml

2. 配置中心:Config → Nacos

Spring Cloud Config(传统)

// Config Server
@EnableConfigServer
@SpringBootApplication
public class ConfigServer {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServer.class, args);
    }
}

// application.yml
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/config-repo
          search-paths: '{application}'

Nacos Config(现代)

# 动态刷新配置
spring:
  application:
    name: user-service
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-extension: yaml
        refresh-enabled: true  # 开启动态刷新

# 在代码中使用
@RestController
@RefreshScope  // 配置变更时自动刷新 Bean
public class ConfigController {
    @Value("${app.feature.flag}")
    private String featureFlag;
}

3. API 网关:Zuul → Gateway

Netflix Zuul(已停止维护)

// Zuul 1.x 阻塞式,性能瓶颈
@EnableZuulProxy
@SpringBootApplication
public class ZuulGateway {
    public static void main(String[] args) {
        SpringApplication.run(ZuulGateway.class, args);
    }
}

Spring Cloud Gateway(现代,基于 WebFlux)

@SpringBootApplication
public class ApiGateway {
    public static void main(String[] args) {
        SpringApplication.run(ApiGateway.class, args);
    }
    
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("order-service", r -> r
                .path("/api/orders/**")
                .filters(f -> f
                    .circuitBreaker(config -> config
                        .setName("orderCB")
                        .setFallbackUri("forward:/fallback/orders"))
                    .stripPrefix(1)
                    .addRequestHeader("X-Gateway-Version", "v2"))
                .uri("lb://order-service"))  // lb:// 代表负载均衡
            .route("payment-service", r -> r
                .path("/api/payments/**")
                .uri("lb://payment-service"))
            .build();
    }
}

高级特性

# 限流配置
spring:
  cloud:
    gateway:
      routes:
      - id: user-service
        uri: lb://user-service
        predicates:
        - Path=/api/users/**
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20

4. 熔断降级:Hystrix → Resilience4j

Hystrix(已停止维护)

// Hystrix 已进入维护模式,不推荐新项目使用
@EnableHystrix
@SpringBootApplication
public class LegacyService {
    // ...
}

Resilience4j(现代推荐,轻量级)

// 使用注解实现熔断
@Service
public class OrderService {
    
    @CircuitBreaker(name = "paymentService", fallbackMethod = "payFallback")
    public String processPayment(Long orderId) {
        // 调用支付服务
        return restTemplate.postForObject(...);
    }
    
    // 降级方法
    public String payFallback(Long orderId, Exception e) {
        return "支付服务暂不可用,订单已保存,请稍后重试";
    }
}

// 配置
resilience4j:
  circuitbreaker:
    instances:
      paymentService:
        failureRateThreshold: 50
        waitDurationInOpenState: 30s
        permittedNumberOfCallsInHalfOpenState: 3
        slidingWindowSize: 10

三、微服务核心模式实现

1. 声明式 HTTP 客户端:Feign

// 定义接口即可,无需实现
@FeignClient(
    name = "user-service", 
    path = "/users",
    fallback = UserServiceFallback.class
)
public interface UserServiceClient {
    
    @GetMapping("/{id}")
    UserDTO getUser(@PathVariable("id") Long id);
    
    @PostMapping
    UserDTO createUser(@RequestBody UserDTO user);
    
    // 支持多参数
    @GetMapping("/search")
    Page<UserDTO> searchUsers(
        @RequestParam("name") String name,
        @RequestParam("page") int page,
        @RequestParam("size") int size);
}

// 降级实现
@Component
public class UserServiceFallback implements UserServiceClient {
    public UserDTO getUser(Long id) {
        return UserDTO.builder().id(id).username("默认用户").build();
    }
    // ... 其他方法
}

2. 负载均衡:Ribbon → LoadBalancer

Ribbon(进入维护模式)

// Ribbon 与 Eureka 集成实现客户端负载均衡
@LoadBalanced  // 自动集成 Ribbon
@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Spring Cloud LoadBalancer(现代,响应式)

// 响应式负载均衡
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
    return WebClient.builder();
}

// 使用
@Service
public class ProductService {
    private final WebClient webClient;
    
    public ProductService(WebClient.Builder builder) {
        this.webClient = builder.baseUrl("lb://product-service").build();
    }
    
    public Mono<ProductDTO> getProduct(Long id) {
        return webClient.get()
            .uri("/products/{id}", id)
            .retrieve()
            .bodyToMono(ProductDTO.class);
    }
}

3. 分布式链路追踪:Sleuth + Zipkin

// 自动注入追踪信息
@SpringBootApplication
public class TraceApplication {
    public static void main(String[] args) {
        SpringApplication.run(TraceApplication.class, args);
    }
}

// 配置
spring:
  zipkin:
    base-url: http://zipkin-server:9411
  sleuth:
    sampler:
      probability: 1.0  # 采样率 100%
    propagation:
      type: w3c,b3  # 支持多种追踪标准

效果:自动在 HTTP Header 中注入 traceIdspanId,实现跨服务调用链追踪。

4. 分布式事务:Seata

// AT 模式(自动补偿)
@Service
public class OrderService {
    
    @GlobalTransactional(name = "createOrder", timeoutMills = 300000)
    public void createOrder(OrderDTO order) {
        // 1. 创建订单(本地事务)
        orderMapper.insert(order);
        
        // 2. 扣减库存(远程服务)
        storageService.deduct(order.getProductId(), order.getCount());
        
        // 3. 扣减余额(远程服务)
        accountService.debit(order.getUserId(), order.getMoney());
        
        // 任一失败,Seata 自动回滚所有分支事务
    }
}

// 配置
seata:
  tx-service-group: my_tx_group
  service:
    grouplist:
      seata-server: 8091

四、完整微服务架构示例

┌─────────────────────────────────────────────────────────────────────┐
│                     API Gateway (Spring Cloud Gateway)              │
│  - 路由:/api/orders → order-service                               │
│  - 限流:10 RPS                                                    │
│  - 熔断:payment-service 失败率>50% 触发                           │
└─────────────────────────────────────────────────────────────────────┘
              ▲                ▲                ▲
              │                │                │
    ┌─────────┼─────────┐ ┌───┴───┐      ┌────┴────┐
    │         │         │ │       │      │         │
┌───▼───┐ ┌──▼───┐ ┌──▼─┐│ ┌───▼───┐│  ┌──▼───┐ ┌──▼──┐
│ Eureka│ │Config│ │Nacos││ │ Zipkin││  │Seata │ │Nacos│
│(or    │ │Server│ │Server││ │ Server││  │Server│ │Config│
│ Consul)│ └──────┘ └──────┘│ └───────┘│  └──────┘ └──────┘
└───────┘                    │          │
              ▲              │          │
              │              │          │
┌─────────────┼──────────────┼──────────┼─────────────────────┐
│             │              │          │                     │
│  ┌──────────▼──┐  ┌───────▼──┐  ┌──▼──────┐  ┌──────────▼──┐│
│  │Order Service│  │Payment   │  │User     │  │Product      ││
│  │   (Feign)   │  │Service   │  │Service  │  │Service      ││
│  └─────────────┘  └──────────┘  └─────────┘  └─────────────┘│
│  端口: 8081     端口: 8082     端口: 8083    端口: 8084   │
└─────────────────────────────────────────────────────────────────┘

部署到 Kubernetes

# order-service-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
  namespace: microservices
spec:
  replicas: 3
  selector:
    matchLabels:
      app: order-service
  template:
    metadata:
      labels:
        app: order-service
      annotations:
        sidecar.istio.io/inject: "true"  # 注入 Istio Sidecar
    spec:
      containers:
      - name: order-service
        image: order-service:1.0.0
        ports:
        - containerPort: 8081
        env:
        - name: SPRING_CLOUD_NACOS_SERVER_ADDR
          value: "nacos-service:8848"

五、与 Kubernetes 和 Service Mesh 的关系

1. 功能重叠与演进

功能Spring CloudKubernetesService Mesh (Istio)
服务发现Eureka/NacosCoreDNS + ServicePilot + Envoy
配置管理Config/NacosConfigMap/Secret不支持(通过 ConfigMap 集成)
负载均衡Ribbon/LoadBalancerKube-proxyEnvoy 高级路由
熔断限流Hystrix/Resilience4j无原生支持DestinationRule
API 网关Gateway/ZuulIngressGateway API + VirtualService
分布式追踪Sleuth + ZipkinJeager/Zipkin 集成
mTLS手动配置基础 NetworkPolicy自动 mTLS
服务网格完整管理

2. 演进趋势:从 Spring Cloud 到 Cloud Native

传统模式(2015-2019):

Spring Cloud Netflix 全家桶 → Dubbo → 自建微服务基础设施

局限:代码侵入性强、语言绑定、运维复杂

云原生模式(2020+):

Spring Cloud → Kubernetes(服务发现、配置) → Service Mesh(流量治理)

现代架构建议

// 轻量化 Spring Cloud,基础设施下沉
@SpringBootApplication
public class ModernService {
    // 1. 服务发现:使用 K8s Service(无需 Eureka)
    // 2. 配置管理:使用 ConfigMap/Secret + Spring Cloud Kubernetes
    // 3. 负载均衡:使用 K8s Service + Istio
    // 4. 熔断限流:使用 Istio DestinationRule + VirtualService
    // 5. 网关:使用 Istio Gateway + Spring Cloud Gateway 轻量层
    // 6. 追踪:保留 Sleuth(自动透传 Header)
}

依赖调整

<!-- 现代轻量化依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-kubernetes-fabric8</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>

六、版本演进与未来发展

1. 版本对齐策略

Spring Cloud 采用 “列车发布模型” ,版本号以伦敦地铁站命名:

Spring Cloud 版本Spring Boot 版本状态支持日期
2022.0.x (Kilburn)3.0.xCurrent2024-12
2021.0.x (Jubilee)2.7.xMaintenance2023-11
2020.0.x (Ilford)2.4.xEOL2022-12
Hoxton2.3.xEOL2022-12

Spring Cloud 2022.0 新变化

2. 下一代架构:服务网格集成

Spring Cloud Gateway 与 Istio 协同

// Gateway 负责业务逻辑路由,Istio 负责流量治理
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("api-route", r -> r
            .path("/api/**")
            .filters(f -> f
                .stripPrefix(1)
                .retry(config -> config.setRetries(3))  // 业务重试
            )
            // 下游由 Istio VirtualService 管理金丝雀发布
            .uri("http://user-service"))
        .build();
}

分布式事务演进:从 Seata 到 Saga 模式 + 事件驱动

// 采用 Spring Cloud Stream + Kafka 实现 Saga
@Service
public class OrderSaga {
    
    @Autowired
    private StreamBridge streamBridge;
    
    public void createOrder(Order order) {
        // 1. 发布事件
        streamBridge.send("order-events", 
            MessageBuilder.withPayload(new OrderCreatedEvent(order)).build());
        
        // 2. 各服务监听事件并执行本地事务
        // 3. 补偿事件处理失败场景
    }
}

七、生产实践建议

1. 项目结构最佳实践

microservice-project/
├── gateway-service          # API 网关(Spring Cloud Gateway)
├── service-registry         # 服务注册中心(Nacos/Consul)
├── config-server            # 配置中心(Nacos Config)
├── order-service            # 订单服务
├── payment-service          # 支付服务
├── user-service             # 用户服务
└── common-components/
    ├── feign-clients        # 共享 Feign 接口定义
    ├── api-dtos             # 共享 DTO
    └── resilience4j-config  # 共享熔断配置

2. 配置管理黄金法则

# bootstrap.yml(引导配置,优先级高于 application.yml)
spring:
  application:
    name: order-service
  cloud:
    nacos:
      config:
        server-addr: ${NACOS_SERVER:localhost:8848}
        namespace: ${NACOS_NAMESPACE:prod}
        group: ${NACOS_GROUP:DEFAULT_GROUP}
        file-extension: yaml
        shared-configs:  # 共享配置
          - data-id: common-redis.yaml
            refresh: true
          - data-id: common-mysql.yaml
            refresh: true
        extension-configs:  # 扩展配置
          - data-id: order-service-ext.yaml
            refresh: true

3. 熔断配置模板

# 通用的 Resilience4j 配置
resilience4j:
  circuitbreaker:
    configs:
      default:
        failureRateThreshold: 50
        slowCallDurationThreshold: 2s
        slowCallRateThreshold: 50
        waitDurationInOpenState: 30s
        permittedNumberOfCallsInHalfOpenState: 3
        minimumNumberOfCalls: 10
        slidingWindowSize: 10
        slidingWindowType: COUNT_BASED
    instances:
      paymentService:
        baseConfig: default
        timeoutDuration: 3s

4. 监控大盘配置

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus,env,beans
  endpoint:
    health:
      show-details: always
  metrics:
    tags:
      application: ${spring.application.name}
    export:
      prometheus:
        enabled: true
  tracing:
    sampling:
      probability: 0.1  # 生产环境 10% 采样率

5. 安全加固

// 服务间认证(Spring Cloud Security + OAuth2)
@EnableResourceServer
@SpringBootApplication
public class SecureService {
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("jwt-secret");
        return converter;
    }
}

// 配置
security:
  oauth2:
    resource:
      jwt:
        key-uri: http://auth-server/oauth/token_key

八、总结与选型建议

Spring Cloud 适用场景

中小型微服务集群:< 100 个服务实例
多语言异构环境:Java 为主,混合 Python/Go
非 K8s 环境:VM 或物理机部署
遗留系统改造:渐进式微服务化

Service Mesh 替代场景

超大规模集群:> 1000 个 Pod
多语言统一治理:Java/Go/Python/Node.js 平等支持
云原生原生:深度使用 Kubernetes
基础设施下沉:将非业务逻辑从代码中移除

混合架构(推荐)

# 最佳实践:Spring Cloud + Istio 混合
# 开发阶段 - 使用 Spring Cloud 快速迭代
# 生产阶段 - 使用 Istio 统一治理
生态系统:
┌────────────────────────────────────────────────────────┐
│   Spring Cloud Gateway (业务路由 + 轻量治理)           │
│   Spring Cloud Alibaba (配置 + 服务发现)               │
│   Spring Cloud Sleuth (追踪 Header 透传)               │
└────────────────────────────────────────────────────────┘
                     ↓
┌────────────────────────────────────────────────────────┐
│   Istio (流量治理 + mTLS + 可观测性)                   │
│   Kubernetes (编排 + 服务发现)                         │
└────────────────────────────────────────────────────────┘

最终建议:在 Kubernetes 成为标准的今天,Spring Cloud 应"轻量化",将基础设施职责逐步让渡给 K8s 和 Service Mesh,自身专注于业务集成层,如声明式客户端、分布式事务、事件驱动等高级抽象,实现从"全家桶"到"精品店"的华丽转身

到此这篇关于Spring Cloud入门详细介绍的文章就介绍到这了,更多相关Spring Cloud入门内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文