Spring Cloud 5 大组件 · 单个服务开发顺序

发布时间:2026/6/14 16:54:44
Spring Cloud 5 大组件 · 单个服务开发顺序 注册中心 → 远程调用 → 负载均衡 → 服务降级 → 网关一、5 大组件的依赖关系开发顺序的灵魂┌──────────────┐ │ 1. 注册中心 │ ← 第 1 步Eureka/Nacos 搭起来 │ (Eureka) │ └──────┬───────┘ │ 服务注册 ↓ ┌──────────────┐ │ 2. 远程调用 │ ← 第 2 步Feign 远程调用其他服务 │ (Feign) │ └──────┬───────┘ │ 调用时 ↓ ┌──────────────┐ │ 3. 负载均衡 │ ← 第 3 步Ribbon 选哪个实例 │ (Ribbon) │ └──────┬───────┘ │ 调用失败 ↓ ┌──────────────┐ │ 4. 服务降级 │ ← 第 4 步Hystrix/Sentinel 熔断 │ (Hystrix) │ └──────┬───────┘ │ 外部访问 ↓ ┌──────────────┐ │ 5. 网关 │ ← 第 5 步Gateway 入口路由 │ (Gateway) │ └──────────────┘核心1 步都不能乱——没有注册中心其他 4 个组件都没法用。二、项目实战4 个 JVM 服务┌──────────────────────┐ │ Eureka Server │ ← 注册中心 │ (8761) │ └──────────┬───────────┘ │ ┌──────────────────────┼──────────────────────┐ │ │ │ ┌───────▼────────┐ ┌────────▼────────┐ ┌───────▼────────┐ │ 报表服务 │ │ 数据采集服务 │ │ 告警服务 │ │ (8081) │ │ (8082) │ │ (8083) │ └────────────────┘ └─────────────────┘ └────────────────┘ ▲ ▲ ▲ │ │ │ └────── Gateway (9000) 网关统一入口 ──────────┘老哥开发 4 个服务的顺序MOVA 项目真实开发流程1.搭 Eureka Server2.搭数据采集服务注册 Eureka3.搭报表服务注册 Eureka Feign 远程调用采集4.搭告警服务注册 Eureka Feign 远程调用报表5.加 Ribbon 负载均衡6.加 Hystrix 熔断7.加 Gateway 网关三、单个服务开发 5 步详解3.1第 1 步注册中心Eureka / Nacos为什么先搞因为没有注册中心服务之间互相找不到。// 1. Eureka Server 启动类 SpringBootApplication EnableEurekaServer // ⚠️ 启用 Eureka Server public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } } // 2. Eureka Server 配置 server: port: 8761 spring: application: name: eureka-server eureka: client: register-with-eureka: false # 自己是 Server fetch-registry: false// 3. 业务服务报表服务启动类 SpringBootApplication EnableEurekaClient // ⚠️ 启用 Eureka Client注册到 Eureka public class ReportApplication { public static void main(String[] args) { SpringApplication.run(ReportApplication.class, args); } } // 4. 业务服务配置 spring: application: name: mova-report-service # ⚠️ 服务名Feign 调用用 eureka: client: service-url: defaultZone: http://eureka-server:8761/eureka/关键点⚠️Eureka Server 自己不注册到 Eurekaregister-with-eureka: false⚠️业务服务启动时自动注册EnableEurekaClient⚠️服务名很重要Feign 调用时用3.2第 2 步远程调用Feign为什么第二步因为服务注册到 Eureka 后才能用服务名远程调用。老哥 MOVA 实战代码报表服务远程调用数据采集服务// 1. Feign 接口声明式 FeignClient(name data-collect-service) // ⚠️ 服务名Eureka 注册的 public interface DataCollectFeignClient { GetMapping(/api/collect/status) ResultCollectStatus getStatus(); PostMapping(/api/collect/exec) ResultVoid execute(RequestBody CollectRequest request); } // 2. 启动类启用 Feign SpringBootApplication EnableEurekaClient EnableFeignClients // ⚠️ 启用 Feign public class ReportApplication { public static void main(String[] args) { SpringApplication.run(ReportApplication.class, args); } } // 3. 业务调用像本地方法 Service public class ReportService { Autowired private DataCollectFeignClient dataCollectClient; public Report generateReport(Long reportId) { // 1. 远程调用数据采集服务 CollectStatus status dataCollectClient.getStatus().getData(); // 2. 业务处理 return processReport(reportId, status); } }关键点⚠️FeignClient(name...)的 name Eureka 注册的服务名⚠️接口的 URL 数据采集服务的 URL不是 Eureka 地址⚠️Feign 自动把方法调用转成 HTTP 请求Feign 自动做的事找 Eureka 拿服务列表用 Ribbon 选一个实例默认轮询发 HTTP 请求把响应反序列化成方法返回值3.3第 3 步负载均衡Ribbon为什么第三步因为Feign 已经集成了 Ribbon默认轮询策略。只需要配策略不写代码。实战配置# application.yml报表服务># application.yml独立 Gateway 服务 server: port: 9000 spring: application: name: mova-gateway cloud: gateway: # 1. 路由配置 routes: - id: mova-report uri: lb://mova-report-service # ⚠️ lb 负载均衡 predicates: - Path/api/mova/** filters: - StripPrefix2 # 去掉 /api/mova 前缀 - id: mpvs-mask uri: lb://mpvs-mask-service predicates: - Path/api/mpvs/** - id: spdb-collect uri: lb://spdb-collect-service predicates: - Path/api/spdb/** # 2. 全局跨域 globalcors: cors-configurations: [/**]: allowedOriginPatterns: * allowedMethods: * # 3. 限流 redis: rate-limiter: replenish-rate: 100 # 每秒 100 个请求 burst-capacity: 200 # 突发 200 个 // 启动类 SpringBootApplication EnableDiscoveryClient // ⚠️ Gateway 也注册到 Eureka public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }关键点⚠️uri: lb://xxx中的lb LoadBalancer自动负载均衡⚠️predicates 路由规则Path / Header / Cookie 等⚠️filters 过滤鉴权 / 限流 / 重写路径Gateway 4 大功能1.路由根据 Path 转发2.鉴权JWT / OAuth23.限流Redis 限流4.熔断Hystrix / Sentinel四、5 大组件协同工作流完整链路外部用户请求 ↓ 1. Gateway 网关9000 端口 ├─ 鉴权JWT 验证 ├─ 限流Redis 限流 100 QPS └─ 路由Path/api/mova/** ↓ 2. Ribbon 负载均衡从 Eureka 拉服务列表选 1 个实例 ↓ 3. Feign 远程调用mova-report-service ↓ 4. Hystrix 熔断保护调用失败熔断返回 Fallback ↓ 5. Eureka 服务发现找 mova-report-service 的 IP:Port ↓ 目标服务执行mova-report-service ↓ 返回结果五、5 大组件的依赖关系5 大组件的依赖顺序就是开发顺序1.注册中心Eureka——基础没有它其他 4 个都没法用2.远程调用Feign——核心用服务名调用其他服务3.负载均衡Ribbon——Feign 自带只配策略不写代码4.服务降级Hystrix——兜底调用失败时返回 Fallback5.网关Gateway——入口所有请求统一入口开发顺序Eureka Server → 数据采集服务 → 报表服务 → 告警服务 → 加 Ribbon → 加 Hystrix → 加 Gateway。六、完整代码模板6.1 父 pom.xml 依赖parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version2.7.18/version /parent properties spring-cloud.version2021.0.8/spring-cloud.version /properties dependencies !-- 1. Eureka 客户端 -- dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-netflix-eureka-client/artifactId /dependency !-- 2. Feign 远程调用 -- dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-openfeign/artifactId /dependency !-- 3. Hystrix 熔断Spring Cloud 2021 改 Resilience4j-- dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-netflix-hystrix/artifactId /dependency !-- 4. Gateway 网关独立服务-- dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-gateway/artifactId /dependency /dependencies7.2 Eureka Server 完整配置# application.ymlEureka Server server: port: 8761 spring: application: name: eureka-server eureka: client: register-with-eureka: false fetch-registry: false service-url: defaultZone: http://eureka-server:8761/eureka/ server: enable-self-preservation: true eviction-interval-timer-in-ms: 50007.3 业务服务完整配置# application.yml报表服务 server: port: 8081 spring: application: name: mova-report-service # 1. Eureka eureka: client: service-url: defaultZone: http://eureka-server:8761/eureka/ instance: prefer-ip-address: true lease-renewal-interval-in-seconds: 30 lease-expiration-duration-in-seconds: 90 # 2. RibbonFeign 自带 data-collect-service: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule ConnectTimeout: 3000 ReadTimeout: 5000 MaxAutoRetries: 1 MaxAutoRetriesNextServer: 2 # 3. Feign Hystrix feign: hystrix: enabled: true client: config: default: connectTimeout: 3000 readTimeout: 5000 hystrix: command: default: execution: timeout: enabled: true isolation: thread: timeoutInMilliseconds: 5000 circuitBreaker: requestVolumeThreshold: 10 errorThresholdPercentage: 50 sleepWindowInMilliseconds: 100007.4 Gateway 完整配置# application.yml独立 Gateway 服务 server: port: 9000 spring: application: name: mova-gateway cloud: gateway: routes: - id: mova-report uri: lb://mova-report-service predicates: - Path/api/mova/** filters: - StripPrefix2 redis: rate-limiter: replenish-rate: 100 burst-capacity: 200七、记忆口诀5 大组件开发顺序注册 → 调用 → 均衡 → 降级 → 网关1 不能乱没有注册中心其他 4 个都用不了Feign 自带 RibbonRibbon 不写代码