五大微服务组件在 RuoYi-Cloud 中的使用方式

五大微服务组件在 RuoYi-Cloud 中的使用方式 一. Nacos — 注册中心 配置中心每个微服务gateway/auth/system/gen/job/file/monitor的 bootstrap.yml 中都配置spring:cloud:nacos:discovery:server-addr: 127.0.0.1:8848 # 服务注册与发现config:server-addr: 127.0.0.1:8848 # 配置中心1.服务发现各服务启动时自动注册到 Nacos服务间通过服务名如 ruoyi-system调用2.配置中心所有运行时配置数据源、Redis、路由、安全白名单等都存储在 Nacos 中项目本地没有 application.yml3.动态刷新通过 RefreshScope 支持配置热更新二. Feign — 声明式 HTTP 客户端服务间调用定义在 ruoyi-api/ruoyi-api-system 中共 3 个 Feign 客户端Feign 接口调用的服务用途RemoteUserServiceruoyi-systemauth 查询用户信息、注册RemoteLogServiceruoyi-system异步保存操作/登录日志RemoteFileServiceruoyi-file上传/删除头像文件关键机制1.自定义注解 EnableRyFeignClients代替 EnableFeignClients扫描所有 com.ruoyi 包2.FeignRequestInterceptor 自动传递 Authorization、用户 ID 等请求头实现服务间认证上下文传递3.全局 Feign 配置在 Nacos 共享配置 application-dev.yml 中feign:sentinel:enabled: true # 开启 Sentinel 熔断okhttp:enabled: true # 使用 OkHttp性能更好client:config:default:connectTimeout: 10000readTimeout: 10000三. LoadBalancer — 客户端负载均衡没有显式配置隐式工作。 Spring Cloud LoadBalancer 在两种场景自动生效1.Feign 调用时FeignClient(value ruoyi-system) → 从 Nacos 获取 ruoyi-system 的多个实例轮询分发2.Gateway 路由时路由配置中 uri: lb://ruoyi-system 的 lb:// 前缀触发负载均衡只在 ruoyi-gateway/pom.xml 显式导入了 spring-cloud-loadbalancer其余服务通过 BOM 依赖传递获得。四. Sentinel — 熔断降级 限流网关层限流最核心# ruoyi-gateway/bootstrap.ymlspring:cloud:sentinel:transport:dashboard: 127.0.0.1:8718 # Sentinel 控制台datasource:ds1:nacos: # 规则持久化到 NacosdataId: sentinel-ruoyi-gatewayrule-type: gw-flow # 网关流控规则Nacos 中存储的限流规则[{ resource: ruoyi-auth, count: 500 }, // 500 QPS{ resource: ruoyi-system, count: 1000 },{ resource: ruoyi-gen, count: 200 },{ resource: ruoyi-job, count: 300 }]Feign 熔断每个 Feign 客户端绑定 fallbackFactory服务不可达时返回 R.fail(...)由 feign.sentinel.enabled: true 启用SentinelFallbackHandler网关限流时返回 请求超过最大数请稍候再试五. Gateway — 统一入口所有请求的唯一入口端口 8080路由定义在 Nacos 的 ruoyi-gateway-dev.ymlspring:cloud:gateway:routes:- id: ruoyi-authuri: lb://ruoyi-auth # 负载均衡到 auth 服务predicates: - Path/auth/**filters:- ValidateCodeFilter # 验证码检查- StripPrefix1 # 去掉 /auth 前缀- id: ruoyi-systemuri: lb://ruoyi-systempredicates: - Path/system/**- id: ruoyi-fileuri: lb://ruoyi-filepredicates: - Path/file/**... # gen、job 类似过滤器链按顺序执行过滤器顺序作用AuthFilter-200全局 — JWT 鉴权校验 Token将用户信息注入请求头XssFilter-100全局 — 清洗 JSON 请求体中的 XSS 攻击ValidateCodeFilter路由级仅对 /auth/login、/auth/register 验证验证码BlackListUrlFilter路由级黑名单 URL 拦截其他功能SpringDocConfig — 聚合所有微服务的 Swagger API 文档GatewayExceptionHandler — 统一异常处理服务未找到、网关错误等/code 端点 — 函数式路由生成验证码图片请求完整流转图浏览器↓Gateway (8080)├─ AuthFilter (JWT 校验)├─ XssFilter (防 XSS)├─ Sentinel (限流检查)└─ 匹配路由 → lb://ruoyi-xxx↓目标微服务 (system/auth/gen/job/file)↓ (Feign 调用)其他微服务 (跨服务通信)↑Nacos (服务发现 配置中心)Sentinel Dashboard (8718) — 控制台监控