当前位置: 首页 > news >正文

spring-cloud-starter-openfeign现实中的运行逻辑

spring-cloud-starter-openfeign现实中的运行逻辑

spring-cloud-starter-openfeign 是 Spring Cloud 生态中声明式的 HTTP 客户端,核心作用是让你像调用本地方法一样调用远程 HTTP 接口,不用手写复杂的 RestTemplate/OkHttp 代码,大幅简化微服务间的通信。

· 声明式:你只需要定义一个接口,加几个注解,Spring 会自动帮你实现接口的 HTTP 调用逻辑,不用写一行请求代码。
· 底层依赖:基于 Netflix Feign 封装,默认用 Spring MVC 注解(@GetMapping/@PostMapping 等),也兼容 Feign 原生注解。
· 核心优势:集成负载均衡(默认 Ribbon)、熔断器(Hystrix/Sentinel)、请求 / 响应拦截、参数解析等,开箱即用。

安装依赖

<!--SpringCloudOpenFeign核心依赖--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId><!--版本建议和SpringCloud版本匹配,比如2023.0.0--><version>2023.0.0</version></dependency><!--若需要负载均衡(微服务必加)--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency>

定义 Feign 客户端接口

假设你要调用远程服务 SC-USER的 /user/{id} 接口:

importorg.springframework.cloud.openfeign.FeignClient;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;// name:远程服务名(注册中心中的服务名),url:本地测试可直接指定地址(非微服务场景)@FeignClient(name=" sc-user")publicinterfaceUserFeignClient{// 完全复用 Spring MVC 注解,和本地 Controller 写法一致@GetMapping("/user/{id}")UserDTOgetUserById(@PathVariable("id")Longid);// 复杂请求示例:POST + 请求体@PostMapping("/user")UserDTOcreateUser(@RequestBodyUserDTOuserDTO);}// 配套的实体类(和远程服务返回结构一致)classUserDTO{privateLongid;privateStringname;privateIntegerage;}

配置路由网关

spring:application:name:sc-gateway cloud:nacos:discovery:server-addr:192.168.0.54:****metadata:region:default# 路由网关配置 gateway:# 设置与服务注册发现组件结合,这样可以采用服务名的路由策略 discovery:locator:enabled:true# 配置路由规则 routes:# 采用自定义路由ID(有固定用法,不同的 id 有不同的功能,详见:https://cloud.spring.io/spring-cloud-gateway/2.0.x/single/spring-cloud-gateway.html#gateway-route-filters)-id:SC-USER# 采用LoadBalanceClient方式请求,以 lb://开头,后面的是注册在Nacos上的服务名 uri:lb://sc-user #Predicate翻译过来是“谓词”的意思,必须,主要作用是匹配用户的请求,有很多种用法 predicates:#Method方法谓词,这里是匹配GETPOST等请求-Path=/user/** filters: - StripPrefix=1 profiles: active: local main: allow-bean-definition-overriding: true banner-mode: "off" #开启sentinel适配feign feign: sentinel: enabled: true ribbon: ReadTimeout: 60000 ConnectTimeout: 60000 management: endpoints: web: exposure: #include: ["beans","metrics","info","health","loggers"] include: "*" security: enabled: false

添加负载均衡

依赖支持

<!--OpenFeign核心依赖--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId><version>2023.0.0</version></dependency><!--负载均衡核心依赖(必须加,否则无法根据服务名寻址)--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency><!--注册中心依赖(以Nacos为例,根据你的注册中心替换)--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId><version>2023.0.1.0</version></dependency>

开启服务发现和 Feign

importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.cloud.client.discovery.EnableDiscoveryClient;importorg.springframework.cloud.openfeign.EnableFeignClients;// 开启服务发现(从注册中心获取实例)@EnableDiscoveryClient// 开启 Feign 客户端扫描@EnableFeignClients@SpringBootApplicationpublicclassFeignConsumerApplication{publicstaticvoidmain(String[]args){SpringApplication.run(FeignConsumerApplication.class,args);}}

调用 Feign 接口(负载均衡自动生效)

importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RestController;importjavax.annotation.Resource;@RestControllerpublicclassUserController{@ResourceprivateUserFeignClientuserFeignClient;@GetMapping("/user/{id}")publicStringgetUser(@PathVariableLongid){// 多次调用会自动分发到不同实例(默认轮询)returnuserFeignClient.getUserById(id);}}

完毕

· OpenFeign 实现负载均衡的核心是「服务名调用 + LoadBalancer 依赖 + 服务发现」,无需手写负载逻辑;

· 关键步骤:引 LoadBalancer 依赖 → 开启服务发现 → FeignClient 只写服务名 → 自动轮询分发请求;

· 可通过配置自定义负载策略(随机 / 权重等),满足不同业务需求。

http://www.jsqmd.com/news/497950/

相关文章:

  • DeepAudit+cpolar效率翻倍让代码审计随时随地高效完成
  • 一级圆柱齿轮减速器——CAD
  • CEO必会之方案设计
  • 基于深度强化学习的虚拟重联列车LQR自适应控制:理论、实现与代码详解
  • Cuckoo沙箱各Ubuntu版本安装及使用_cuckoo sandbox 安装
  • Claude Code 最佳实践:可验证、可治理、可分层的工程现实
  • 计算机毕业设计Django+大模型中华古诗词知识图谱可视化 古诗词智能问答系统 古诗词数据分析 古诗词情感分析模型 自然语言处理NLP 机器学习 深度学习
  • 多目标蜣螂优化算法NSDBO在微电网多目标优化调度中的应用:Matlab语言解决方案
  • 自动驾驶智能大脑分工合作:德州农工大学让AI既能思考又能开车
  • 2059:【例3.11】买笔
  • python-flask校园二手书交易系统_django pycharm vue
  • 解决 ggplot Scale for ‘fill‘ is already present. Adding another scale for ‘fill‘, which will replace
  • 大数据领域Spark的资源管理与调度
  • 软件加密狗中时间限制机制的破解
  • 【避坑封神】Ubuntu24.04 适配 CUDA12.9 装 CUDNN 9.x:从 apt 报错到 Test passed! 全程拆解
  • Score Distillation Sampling(SDS)
  • 二十、Kubernetes基础-13-kubeadm-ha-kubernetes-deployment-guide-03-haproxy-keepalived
  • Visualbasic6.0引用问题
  • Nest.js 入门:从 0 到 1 掌握企业级 Node.js 框架(新手也能秒懂模块/控制器/服务)
  • AI之Transform encoder/decoder抽象理解
  • 2026年多账号运营下浏览器指纹关联风险与防护方案研究
  • 【C语言学习笔记】(1)
  • 2026前端面试题和避坑指南
  • 风速仿真模型实现及代码详解
  • 吃透HTTP及相关协议核心区别,从基础到进阶全覆盖
  • 【AI】如何设计Agent的记忆系统?
  • 探索同城招聘系统源码:企业端+求职者端功能开发全流程详解
  • 阿里发布全球首个企业级Agent平台“悟空”,要把“龙虾”装进2000万企业组织里
  • python+Ai技术的学生课外活动管理系统的数据可视化大屏分析系统 _
  • Mixture of Experts(MoE)