news 2026/4/3 6:38:47

Spring Cloud OpenFeign.D.1:详述及示例

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Spring Cloud OpenFeign.D.1:详述及示例

Spring Cloud OpenFeign

1、概述

文档:https://spring.io/projects/spring-cloud-openfeign

该项目通过自动配置以及与 Spring 环境及其他 Spring 编程模型惯用方法的绑定,为 Spring Boot 应用程序提供了 https://github.com/OpenFeign/feign[OpenFeign] 的集成支持。

特征

  • 声明式 REST 客户端:Feign 会为带有 JAX-RS 或 Spring MVC 注解修饰的接口创建一个动态实现。

开始

@SpringBootApplication @EnableFeignClients public class WebApplication { public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); } @FeignClient("name") static interface NameService { @RequestMapping("/") public String getName(); } }

2、介绍

文档:https://docs.spring.io/spring-cloud-openfeign/reference/index.html

本项目通过自动配置以及与 Spring 环境的绑定以及遵循其他 Spring 编程模型的惯用方法,为 Spring Boot 应用程序提供了 OpenFeign 的集成功能。

正如在《Spring Cloud 2022.0.0 发布博客文章》中所宣布的那样,我们现在已将 Spring Cloud OpenFeign 项目视为功能完备。我们将仅添加错误修复内容,并可能合并一些来自社区的小型功能提案。我们建议转而使用 Spring HTTP Service Clients.。

一、Features(特征)

文档:https://docs.spring.io/spring-cloud-openfeign/reference/spring-cloud-openfeign.html

声明式 REST 客户端:Feign

Feign 是一种声明式的网络服务客户端。它使得编写网络服务客户端变得更加容易。要使用 Feign,需创建一个interface(接口)并对其进行标注。它具有可插拔的注解支持,包括 Feign 注解和 JAX-RS 注解。Feign 还支持可插拔的编码器和解码器。Spring Cloud 增加了对 Spring MVC 注解的支持,并支持使用 Spring Web 中默认使用的相同的HttpMessageConverters。Spring Cloud 将 Eureka、Spring Cloud CircuitBreaker 以及 Spring Cloud LoadBalancer 集成在一起,以便在使用 Feign 时提供一个负载均衡的 HTTP 客户端。

1、如何引入 Feign

要在您的项目中引入 Feign,请使用具有org.springframework.cloudgroup 和spring-cloud-starter-openfeignartifactId的启动器。有关使用当前 Spring Cloud 发布版设置构建系统的详细信息,请参阅 Spring Cloud Project。

示例 Spring Boot 应用程序

@SpringBootApplication @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

StoreClient.java

@FeignClient("stores") public interface StoreClient { @RequestMapping(method = RequestMethod.GET, value = "/stores") List<Store> getStores(); @GetMapping("/stores") Page<Store> getStores(Pageable pageable); @PostMapping(value = "/stores/{storeId}", consumes = "application/json", params = "mode=upsert") Store update(@PathVariable("storeId") Long storeId, Store store); @DeleteMapping("/stores/{storeId:\\d+}") void delete(@PathVariable Long storeId); }

@FeignClient注解中,字符串值(如上述的“stores”)是一个任意的客户端名称,用于创建一个 Spring Cloud LoadBalancer client(负载均衡)。您还可以使用 url 属性(绝对值或仅主机名)来指定一个 URL。应用程序上下文中的 bean 名称是接口的完全限定名称。如果您要指定自己的别名值,可以使用 @FeignClient 注解的qualifiers值。

上述的load-balancer(负载均衡器)客户端将需要获取"stores"服务的物理地址。如果您的应用程序是 Eureka 客户端,那么它会从 Eureka 服务注册表中解析该服务。如果您不想使用 Eureka,也可以通过使用SimpleDiscoveryClient在外部配置中配置服务器列表。

Spring Cloud OpenFeign 支持 Spring Cloud LoadBalancer(负载均衡)的blocking mode(阻塞模式)所具备的所有功能。您可以在project documentation中了解更多相关内容。

若要在带有@Configuration注解的类中使用@EnableFeignClients注解,请务必明确指定客户端所在的包路径,例如:

@EnableFeignClients(basePackages = "com.example.clients") 或者明确列出它们 @EnableFeignClients(clients = InventoryServiceFeignClient.class)

在多模块设置中加载 Spring Feign 客户端 bean 时,您需要直接指定相关包。

由于 FactoryBean 对象可能在初始上下文刷新之前就被实例化,而 Spring Cloud OpenFeign 客户端的实例化会触发上下文刷新,因此这些对象不应在 FactoryBean 类中进行声明。

属性解析模式

在创建 Feign 客户端 bean 时,我们会解析通过 @FeignClient 注解传递的值。自 4.x 版本起,这些值是被立即解析的。对于大多数用例来说,这是一个很好的解决方案,并且还支持 AOT(提前编译)。

如果您希望属性的解析是延迟进行的,请将 spring.cloud.openfeign.lazy-attributes-resolution 属性的值设置为 true 。

对于 Spring Cloud Contract 测试集成,应使用延迟属性解析功能。

2、覆盖Feign默认设置

Spring Cloud 的 Feign 支持中的一个核心概念是“命名客户端”。每个 Feign 客户端都是一个组件集合的一部分,这些组件协同工作以根据需要联系远程服务器,而这个集合有一个名称,作为应用程序开发人员使用 @FeignClient 注解时所赋予的。Spring Cloud 会根据每个命名客户端的需求在ApplicationContext中创建一个新的集合,使用FeignClientsConfiguration进行处理。这包含(以及其他内容)feign.Decoder,feign.Encoderfeign.Contract.。可以通过使用@FeignClient注解的contextId属性来覆盖这个集合的名称。

Spring Cloud 允许您通过使用@FeignClient注解来声明额外的配置(在FeignClientsConfiguration的基础上),从而完全掌控 Feign 客户端。示例:

@FeignClient(name = "stores", configuration = FooConfiguration.class) public interface StoreClient { //.. }

在这种情况下,客户端是由FeignClientsConfiguration中已有的组件以及FooConfiguration中的任何组件组合而成的(其中后者会覆盖前者)。

FooConfiguration无需使用@Configuration进行标注。但如果使用了该注解,则需注意将其排除在任何会将此配置包含在内的@ComponentScan中之外,因为这样一来,它将成为 feign 的默认数据源,包括feign.Decoder,feign.Encoder,feign.Contract等相关组件。为避免这种情况,可以将其放在与任何@ComponentScan@SpringBootApplication不重叠的单独包中,或者在@ComponentScan中明确排除它。
通过在@FeignClient注解中使用contextId属性,并同时更改ApplicationContext集合的名称,将能够覆盖客户端名称的别名,并将其用作为该客户端所创建的配置 bean 名称的一部分。

S.1、Spring Cloud OpenFeign在Nacos中集成示例

1、父POM

(示例:openfeign-nacos-b3-example)

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example.springcloud.openfeign</groupId> <artifactId>openfeign-nacos-b3-example</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>openfeign-nacos-provider-example</module> <module>openfeign-nacos-consumer-example</module> </modules> <properties> <!-- Spring Cloud Alibaba --> <spring.cloud.alibaba.version>2025.0.0.0</spring.cloud.alibaba.version> <!-- Spring Cloud --> <spring.cloud.version>2025.0.0</spring.cloud.version> <!-- Spring Boot --> <spring.boot.version>3.5.8</spring.boot.version> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> </properties> <dependencyManagement> <dependencies> <!-- Spring Boot BOM --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring.boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> <!-- Spring Cloud BOM --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring.cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <!-- Spring Cloud Alibaba BOM --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${spring.cloud.alibaba.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </pluginManagement> </build> </project>

2、服务提供者(注册到Nacos)

(示例:openfeign-nacos-provider-example),提供一个最简单的服务,并把服务注册到Nacos中。

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>openfeign-nacos-b3-example</artifactId> <groupId>org.example.springcloud.openfeign</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>openfeign-nacos-provider-example</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- SpringCloud Alibaba Nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies> </project>

2.application.yaml

server: port: 9001 spring: application: name: openfeign-nacos-provider-example cloud: nacos: discovery: server-addr: 192.168.0.227:8848

3.启动类(OpenFeignNacosProviderApplication)

package org.example.openfeign.provider; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class OpenFeignNacosProviderApplication { public static void main(String[] args) { SpringApplication.run(OpenFeignNacosProviderApplication.class, args); } }

4.提供一个服务(HelloController)

package org.example.openfeign.provider.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "hello world"; } }

5.结果

注册到Nacos中

访问结果

3、服务消费者

(示例:openfeign-nacos-consumer-example),既是服务消费者也是服务提供者。

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>openfeign-nacos-b3-example</artifactId> <groupId>org.example.springcloud.openfeign</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>openfeign-nacos-consumer-example</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- SpringCloud Alibaba Nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!--OpenFeign为HTTP形式的Rest API提供了非常简洁高效的RPC调用方式--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!--loadbalancer是Spring Cloud官方自己提供的客户端负载均衡器,抽象和实现,用来替代Ribbon--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-loadbalancer</artifactId> </dependency> </dependencies> </project>

2.application.yaml

server: port: 9002 spring: application: name: openfeign-nacos-consumer-example cloud: nacos: discovery: server-addr: 192.168.0.227:8848

3.启动类(OpenFeignNacosConsumerApplication)

package org.example.openfeign.consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class OpenFeignNacosConsumerApplication { public static void main(String[] args) { SpringApplication.run(OpenFeignNacosConsumerApplication.class, args); } }

4.Feign Client(HelloClient)

package org.example.openfeign.consumer.openfeignclients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; // 括号中为目标服务名 @FeignClient("openfeign-nacos-provider-example") public interface HelloClient { // 目标方法的url @GetMapping("hello") String hello(); }

5.消费者(ConsumerController)

package org.example.openfeign.consumer.controller; import org.example.openfeign.consumer.openfeignclients.HelloClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Date; @RestController public class ConsumerController { @Autowired HelloClient helloClient; @GetMapping("/feign") public String test() { return helloClient.hello()+" from Feign at "+new Date(); } }

6.结果

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/2 6:01:40

2026金三银四最新一线大厂Java八股文合集强势开源

前言 现在已经2月了&#xff0c;还有一个月就是3月了。大家都知道每年的3月和4月都是互联网大厂疯狂招人的黄金期&#xff0c;也就是程序员的黄金跳槽期&#xff0c;所以被称为金三银四。 无论你是刚出校园大门的菜鸟&#xff0c;还是对跳槽蓄谋已久的老手&#xff0c;都会在这…

作者头像 李华
网站建设 2026/3/31 8:32:11

真的太省时间了!AI论文网站 千笔 VS 笔捷Ai,自考写论文神器!

随着人工智能技术的迅猛发展&#xff0c;AI辅助写作工具正逐步成为高校学生完成毕业论文的重要助手。无论是开题报告、文献综述还是整篇论文的撰写&#xff0c;越来越多的学生开始借助AI工具提升效率、降低写作难度。然而&#xff0c;面对市场上功能各异、水平参差不齐的AI写作…

作者头像 李华
网站建设 2026/4/2 22:52:30

程序员必看:大模型岗位技能图谱与求职指南(收藏版)_大模型工作岗位解析和大模型项目经理工作职责

本文全面介绍了大模型领域的各类岗位及其要求&#xff0c;包括技术类的算法工程师、研发工程师和管理类的AI项目经理、产品经理、销售及解决方案专家。详细分析了各岗位所需的技能和经验&#xff0c;提供了求职渠道&#xff0c;并分享了学习路线和资源&#xff0c;帮助零基础小…

作者头像 李华
网站建设 2026/3/28 6:36:52

【数学思维】

数学思维 主动忘掉“东西是什么”&#xff0c;只保留“它们之间哪些关系必须被保留”。

作者头像 李华
网站建设 2026/3/14 10:48:20

今日首发|Claude Opus 4.6重磅更新,一步API可直接接入

重磅消息&#xff01;Anthropic今日正式推出旗舰级大模型——Claude Opus 4.6&#xff0c;全方位升级核心能力&#xff0c;新增多项实用功能。 更关键的是&#xff0c;无需复杂配置&#xff0c;通过一步API就能快速接入&#xff0c;新手开发者也能轻松上手&#xff0c;彻底降低…

作者头像 李华