Spring Cloud OpenFeign快速入门demo

[复制链接]
发表于 2025-11-22 15:50:02 来自手机 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
一、应用场景

Spring Cloud OpenFeign 是一个声明式的 HTTP 客户端,旨在简化微服务之间的通讯。它使得开辟者可以大概通过简单的接口界说和注解来调用 RESTful API,极大地镌汰了样板代码。以下是一些典范的应用场景:

  • 微服务间调用:在微服务架构中,服务之间必要频仍地举行 HTTP 调用,OpenFeign 提供了一种简便的方式来实现这些调用。
  • RESTful API 客户端:当必要与外部 RESTful API 举行交互时,OpenFeign 可以资助快速构建客户端。
  • 服务发现:与 Eureka 等服务发现组件团结利用时,OpenFeign 可以自动处理处罚服务的负载均衡和故障转移。
  • 动态设置:在必要根据差异环境或条件动态设置哀求时,OpenFeign 提供了机动的办理方案。
二、原理

Spring Cloud OpenFeign 的核心原理是利用 Java 的动态署理和注解来简化 HTTP 哀求的构建。开辟者只需界说接口,并利用注解形貌哀求的细节(如 HTTP 方法、路径、参数等),在运行时,OpenFeign 会天生实现类并处理处罚哀求。
重要组件


  • Feign Client:界说服务接口,利用注解形貌哀求。
  • Request Interceptor:用于在哀求发送之前对哀求举行修改(如添加 header)。
  • Encoder/Decoder:用于哀求和相应的编码息争码,支持 JSON、XML 等格式。
  • 错误处理处罚:提供自界说的错误处理处罚机制,以便在哀求失败时举行处理处罚。
三、代码示例

1. 添加依赖

在 Maven 项目的 pom.xml 中添加 OpenFeign 依赖:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5.     <parent>
  6.         <artifactId>springcloud-demo</artifactId>
  7.         <groupId>com.et</groupId>
  8.         <version>1.0-SNAPSHOT</version>
  9.     </parent>
  10.     <modelVersion>4.0.0</modelVersion>
  11.     <artifactId>spring-cloud-openfeign</artifactId>
  12.     <properties>
  13.         <maven.compiler.source>17</maven.compiler.source>
  14.         <maven.compiler.target>17</maven.compiler.target>
  15.     </properties>
  16.     <dependencies>
  17.         <dependency>
  18.             <groupId>org.springframework.cloud</groupId>
  19.             <artifactId>spring-cloud-starter-openfeign</artifactId>
  20.         </dependency>
  21.         <dependency>
  22.             <groupId>org.springframework.boot</groupId>
  23.             <artifactId>spring-boot-starter-web</artifactId>
  24.         </dependency>
  25.         <dependency>
  26.             <groupId>org.springframework.boot</groupId>
  27.             <artifactId>spring-boot-starter-actuator</artifactId>
  28.         </dependency>
  29.         <dependency>
  30.             <groupId>org.springframework.boot</groupId>
  31.             <artifactId>spring-boot-starter-test</artifactId>
  32.             <scope>test</scope>
  33.         </dependency>
  34.         <dependency>
  35.             <groupId>org.springframework.boot</groupId>
  36.             <artifactId>spring-boot-starter-aop</artifactId>
  37.         </dependency>
  38.         <dependency>
  39.             <groupId>org.projectlombok</groupId>
  40.             <artifactId>lombok</artifactId>
  41.         </dependency>
  42.     </dependencies>
  43. </project>
复制代码
2. 启用 OpenFeign

在 Spring Boot 应用的主类上添加 @EnableFeignClients 注解:
  1. package com.et;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.openfeign.EnableFeignClients;
  5. @SpringBootApplication
  6. @EnableFeignClients
  7. public class MyApplication {
  8.     public static void main(String[] args) {
  9.         SpringApplication.run(MyApplication.class, args);
  10.     }
  11. }
复制代码
3. 界说 Feign Client

创建一个 Feign Client 接口,利用注解界说哀求:
  1. package com.et.service;
  2. import com.et.model.User;
  3. import org.springframework.cloud.openfeign.FeignClient;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. @FeignClient(name = "user-service", url = "http://localhost:8088")
  7. public interface UserServiceClient {
  8.     @GetMapping("/user/{id}")
  9.     User getUserById(@PathVariable("id") Long id);
  10. }
复制代码
4. 利用 Feign Client

在服务中利用 Feign Client:
  1. package com.et.controller;
  2. import com.et.model.User;
  3. import com.et.service.UserService;
  4. import jakarta.servlet.http.HttpServletRequest;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @RestController
  10. public class UserController {
  11.     @Autowired
  12.     private UserService userService;
  13.     @GetMapping("/users/{id}")
  14.     public User getUser(@PathVariable Long id) {
  15.         return userService.getUser(id);
  16.     }
  17.     @GetMapping("/user/{id}")
  18.     public User user(@PathVariable Long id, HttpServletRequest request) {
  19.         // get username and password from header
  20.         String userHeader = request.getHeader("user");
  21.         String passwordHeader = request.getHeader("password");
  22.         // print params
  23.         System.out.println("User Header: " + userHeader);
  24.         System.out.println("Password Header: " + passwordHeader);
  25.         User  user =   new User();
  26.         user.setId(id);
  27.         user.setEmail("xxx@xx.com");
  28.         user.setName("test");
  29.         return user;
  30.     }
  31. }
复制代码
四、拦截器

OpenFeign 允许你利用哀求拦截器来修改哀求,比方添加 header、日记记载等。以下是怎样实现一个简单的哀求拦截器:
1. 创建拦截器

  1. package com.et.interceptor;
  2. import feign.RequestInterceptor;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. /**
  7. * @author liuhaihua
  8. * @version 1.0
  9. * @ClassName JSONPlaceHolderInterceptor
  10. * @Description todo
  11. * @date 2024/12/23/ 14:18
  12. */
  13. @Configuration
  14. public class JSONPlaceHolderInterceptor  {
  15.     @Value("${feign.client.config.default.username}")
  16.     private String username;
  17.     @Value("${feign.client.config.default.password}")
  18.     private String password;
  19.     @Bean
  20.     public RequestInterceptor requestInterceptor() {
  21.         return requestTemplate -> {
  22.             requestTemplate.header("user", username);
  23.             requestTemplate.header("password", password);
  24.             requestTemplate.header("Accept", "application/json");
  25.         };
  26.     }
  27. }
复制代码
2. 在 Feign Client 中利用拦截器

  1. server:
  2.   port: 8088
  3. feign:
  4.   client:
  5.     config:
  6.       default:
  7.         username: xxxx
  8.         password: password
  9.         requestInterceptors:
  10.           com.et.interceptor.JSONPlaceHolderInterceptor
复制代码
以上只是一些关键代码,全部代码请拜见下面代码堆栈
代码堆栈



  • https://github.com/Harries/springcloud-demo(Spring Cloud Openfeign)
五、测试

启动Spring CLoud应用,访问http://127.0.0.1:8088/users/1,返回效果如下
  1. {"id":1,"name":"test","email":"xxx@xx.com"}
复制代码
检察控制台,发现得到拦截器设置的值
  1. User Header: xxxx
  2. Password Header: password
复制代码
l六、总结

Spring Cloud OpenFeign 是一个强大的工具,可以大概简化微服务之间的 HTTP 调用。通过声明式的方式,开辟者可以快速构建 RESTful 客户端,镌汰样板代码,进步开辟服从。团结哀求拦截器,OpenFeign 还可以机动地处理处罚哀求的各种需求,如身份验证和日记记载。
在微服务架构中,利用 OpenFeign 可以有效地进步服务间的通讯服从和可维护性,是构建当代分布式体系的告急构成部分。通过简单的设置和注解,开辟者可以大概专注于业务逻辑,而不必过多关注底层的 HTTP 哀求细节。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表