声明式服务调用SpringCloud Feign

柔光的暖阳◎ 2022-12-07 12:43 264阅读 0赞

声明式服务调用SpringCloud Feign

前面使用了Ribbon做客户端负载均衡,使用Hystrix做容错保护,这两者被作为基础工具类框架被广泛地应用在各个微服务的实现中。SpringCloudFeign是将两者做了更高层次的封装以简化开发。它基于Netfix Feign实现,整合了SpringCloudRibbon和SpringCloudHystrix,除了提供这两者的强大功能外,还提供了一种声明是的Web服务客户端定义的方式。SpringCloudFeign在NetFixFeign的基础上扩展了对SpringMVC注解的支持,在其实现下,我们只需创建一个接口并用注解的方式来配置它,即可完成对服务提供方的接口绑定。简化了SpringCloudRibbon自行封装服务调用客户端的开发量。

快速入门

创建项目 feign-consumer,其余代码可参考上一章的代码。

pom 依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.cloud</groupId>
  8. <artifactId>spring-cloud-starter-eureka</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter-feign</artifactId>
  13. </dependency>
  14. </dependencies>

创建应用启动类

创建应用启动类,并通过 @EnableFeignClients 注解开启 Spring Cloud Feign 的支持功能

  1. package com;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  5. import org.springframework.cloud.netflix.feign.EnableFeignClients;
  6. @EnableFeignClients
  7. @EnableDiscoveryClient
  8. @SpringBootApplication
  9. public class Application {
  10. public static void main(String[] args) {
  11. SpringApplication.run(Application.class, args);
  12. }
  13. }

定义 HelloService 接口

定义 HelloService 接口,通过 @FeignClient 注解指定服务名来绑定服务,然后再使用 SpringMVC 的注解来绑定具体该服务提供的 REST 接口

这里服务名不区分大小写,所以使用 SERIVCE-USER 和 service-user 都是可以的

  1. package com.controller;
  2. import org.springframework.cloud.netflix.feign.FeignClient;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. @FeignClient("hello-service")
  5. public interface HelloService {
  6. @RequestMapping("/hello")
  7. String hello();
  8. }

方法调用

  1. package com.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class ConsumerController {
  8. @Autowired
  9. HelloService helloService;
  10. @RequestMapping(value = "ribbon-consumer", method = RequestMethod.GET)
  11. public String helloConsumer() {
  12. return helloService.hello();
  13. }
  14. }

配置文件

  1. spring.application.name=feign-consumer
  2. server.port=9000
  3. eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
  4. #修改缓存清单的更新时间,该值默认为30s
  5. eureka.client.registry-fetch-interval-seconds=30

测试

依次启动服务注册中心、服务提供方、服务消费方。然后访问http://localhost:9000/ribbon-consumer,有时候可以正常返回数据,不断刷新几次地址,可以发现feign通过轮询实现了客户端负载均衡。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rtWmRAcX-1600188406570)(media/1546395519194.png)]

参数绑定

hello-service改造

增加方法

hello-service中多增加一些接口 ,其中包含带有request参数的请求、带有header信息的请求、带有requestbody的请求以及请求响应体是一个对象的请求。

  1. package com.web;
  2. import org.apache.log4j.Logger;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.cloud.client.ServiceInstance;
  5. import org.springframework.cloud.client.discovery.DiscoveryClient;
  6. import org.springframework.web.bind.annotation.*;
  7. import java.util.Random;
  8. @RestController
  9. public class HelloController {
  10. private final Logger logger = Logger.getLogger(getClass());
  11. @Autowired
  12. private DiscoveryClient client;
  13. @RequestMapping(value = "/hello", method = RequestMethod.GET)
  14. public String hello() throws Exception {
  15. ServiceInstance instance = client.getLocalServiceInstance();
  16. // 测试超时触发断路器
  17. int sleepTime = new Random().nextInt(3000);
  18. logger.info("sleepTime:" + sleepTime);
  19. Thread.sleep(sleepTime);
  20. logger.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
  21. return "Hello World";
  22. }
  23. @RequestMapping(value = "/hello1", method = RequestMethod.GET)
  24. public String hello(@RequestParam String name) {
  25. return "Hello1 " + name;
  26. }
  27. @RequestMapping(value = "/hello2", method = RequestMethod.GET)
  28. public User hello(@RequestHeader String name, @RequestHeader Integer age) {
  29. return new User(name, age);
  30. }
  31. @RequestMapping(value = "/hello3", method = RequestMethod.POST)
  32. public String hello(@RequestBody User user) {
  33. return "Hello3 " + user.getName() + ", " + user.getAge();
  34. }
  35. }

构造 User对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lpMNRgfq-1600188406571)(media/1546398184529.png)]

增加User 对象如下, 这里必须要有 User 的默认构造函数,不然 Spring Cloud Feign 根据 JSON 字符串转换 User 对象会抛出异常。

  1. package com.web;
  2. public class User {
  3. private String name;
  4. private Integer age;
  5. public User() {
  6. }
  7. public User(String name, Integer age) {
  8. this.name = name;
  9. this.age = age;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public Integer getAge() {
  18. return age;
  19. }
  20. public void setAge(Integer age) {
  21. this.age = age;
  22. }
  23. @Override
  24. public String toString() {
  25. return "name=" + name + ", age=" +age;
  26. }
  27. }

feign-consumer改造

增加user对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lvKw5yNp-1600188406572)(media/1546396616427.png)]

接口绑定声明

直接将上面添加的接口复制到消费方的Service接口中,删除方法体。需要注意的是:在SpringMVC中@RequestParam和@RequestHeader注解,如果我们不指定value,则默认采用参数的名字作为其value,但是在Feign中,这个value必须明确指定,否则会报错

  1. package com.controller;
  2. import org.springframework.cloud.netflix.feign.FeignClient;
  3. import org.springframework.web.bind.annotation.*;
  4. @FeignClient("hello-service")
  5. public interface HelloService {
  6. @RequestMapping(value = "/hello", method = RequestMethod.GET)
  7. public String hello();
  8. @RequestMapping(value = "/hello1", method = RequestMethod.GET)
  9. public String hello(@RequestParam("name") String name);
  10. @RequestMapping(value = "/hello2", method = RequestMethod.GET)
  11. public User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age);
  12. @RequestMapping(value = "/hello3", method = RequestMethod.POST)
  13. public String hello(@RequestBody User user);
  14. }

测试接口

  1. @RequestMapping(value = "feign-consumer2", method = RequestMethod.GET)
  2. public String helloConsumer1() {
  3. StringBuilder sb = new StringBuilder();
  4. sb.append(helloService.hello()).append("\n");
  5. sb.append(helloService.hello("DIDI")).append("\n");
  6. sb.append(helloService.hello("DIDI", 30)).append("\n");
  7. sb.append(helloService.hello(new User("DIDI", 30))).append("\n");
  8. return sb.toString();
  9. }

访问http://localhost:9000/feign-consumer2

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fQnowY5q-1600188406574)(media/1546397504495.png)]

继承特性

根据上面参数绑定的做法,我们需要进行很多接口的copy操作,这样比较麻烦,可以通过继承的方式进行简化。

创建API模块

导入依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com</groupId>
  6. <artifactId>service-api</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>service-api</name>
  9. <description>Demo project for Spring Boot</description>
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>1.3.7.RELEASE</version>
  14. <relativePath/>
  15. </parent>
  16. <properties>
  17. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18. <java.version>1.8</java.version>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. </dependencies>
  26. </project>

复制user类

复制上节中的 User 对象到 service-api 工程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L9r9ws1U-1600188406575)(media/1546398291662.png)]

创建 HelloService 接口

  1. package com.serviceapi.service;
  2. import com.serviceapi.domain.User;
  3. import org.springframework.web.bind.annotation.*;
  4. @RequestMapping("/refactor")
  5. public interface HelloService {
  6. @RequestMapping(value = "/hello", method = RequestMethod.GET)
  7. public String hello();
  8. @RequestMapping(value = "/hello1", method = RequestMethod.GET)
  9. public String hello(@RequestParam("name") String name);
  10. @RequestMapping(value = "/hello2", method = RequestMethod.GET)
  11. public User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age);
  12. @RequestMapping(value = "/hello3", method = RequestMethod.POST)
  13. public String hello(@RequestBody User user);
  14. }

重构hello-service

导入依赖

  1. <dependency>
  2. <groupId>com</groupId>
  3. <artifactId>service-api</artifactId>
  4. <version>0.0.1-SNAPSHOT</version>
  5. </dependency>

删除user类

重写服务提供类

  1. package com.web;
  2. import com.serviceapi.domain.User;
  3. import com.serviceapi.service.HelloService;
  4. import org.springframework.web.bind.annotation.*;
  5. import java.util.Random;
  6. @RestController
  7. public class HelloController implements HelloService {
  8. @Override
  9. public String hello() throws Exception {
  10. // 测试超时触发断路器
  11. int sleepTime = new Random().nextInt(3000);
  12. Thread.sleep(sleepTime);
  13. return "Hello World";
  14. }
  15. @Override
  16. public String hello(@RequestParam("name") String name) {
  17. return "Hello " + name;
  18. }
  19. @Override
  20. public User hello(@RequestHeader("name")String name, @RequestHeader("age")Integer age) {
  21. return new User(name, age);
  22. }
  23. @Override
  24. public String hello(@RequestBody User user) {
  25. return "Hello "+ user.getName() + ", " + user.getAge();
  26. }
  27. }

重构feign-consumer

创建 RefactorHelloService 接口

  1. package com.controller;
  2. import com.serviceapi.service.HelloService;
  3. import org.springframework.cloud.netflix.feign.FeignClient;
  4. @FeignClient(value = "hello-service")
  5. public interface RefactorHelloService extends HelloService {
  6. }

删除User类和HelloService 接口

测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PIAgoT3M-1600188406576)(media/1546480393877.png)]

优点和缺点

  • 优点

可以很方便的实现接口定义和依赖的共享,不再使用复制粘贴接口进行绑定。

  • 缺点

接口的变动就会对项目构建造成影响,可能服务提供方修改了一个接口定义,那么会导致客户端工程的构建失败。

好像无法使用服务降级功能。

Ribbon 配置

全局配置

全局配置的方法非常简单,我们可以直接使用ribbon.=的方式来设置ribbon的各项默认参数。如下:

  1. #以下配置全局有效
  2. ribbon.eureka.enabled=true
  3. #建立连接超时时间,原1000
  4. ribbon.ConnectTimeout=60000
  5. #请求处理的超时时间,5分钟
  6. ribbon.ReadTimeout=60000
  7. #所有操作都重试
  8. ribbon.OkToRetryOnAllOperations=true
  9. #重试发生,更换节点数最大值
  10. ribbon.MaxAutoRetriesNextServer=10
  11. #单个节点重试最大值
  12. ribbon.MaxAutoRetries=1

指定服务配置

大多数情况下,我们对于服务调用的超时时间可能会根据实际服务的特性做一些调整,所以仅仅进行个性化配置的方式与使用Spring Cloud Ribbon时的配置方式是意义的,都采用.ribbon.key=value的格式进行设置。但是,这里就有一个疑问了,所指代的Ribbon客户端在那里呢?

回想一下,在定义Feign客户端的时候,我们使用了@FeignClient注解。在初始化过程中,Spring Cloud Feign会根据该注解的name属性或value属性指定的服务名,自动创建一个同名的Ribbon客户端。如下:

  1. #以下配置对服务hello-service-provider有效
  2. hello-service.ribbon.eureka.enabled=true
  3. #建立连接超时时间
  4. hello-service.ribbon.ConnectTimeout=500
  5. #请求处理的超时时间
  6. hello-service.ribbon.ReadTimeout=2000
  7. #所有操作都重试
  8. hello-service.ribbon.OkToRetryOnAllOperations=true
  9. #重试发生,更换节点数最大值
  10. hello-service.ribbon.MaxAutoRetriesNextServer=2
  11. #单个节点重试最大值
  12. hello-service.ribbon.MaxAutoRetries=1

重试机制

feign-consumer 添加之前上述指定服务配置

访问http://localhost:9000/feign-consumer

在 user-service 可以看到控制台的两个服务提供者有时会打印出如下信息:

Ribbon超时与Hystrix超时问题,为了确保Ribbon重试的时候不被熔断,我们就需要让Hystrix的超时时间大于Ribbon的超时时间,否则Hystrix命令超时后,该命令直接熔断,重试机制就没有任何意义了。

从上面的配置来说,ribbon超时配置为1800,请求超时后,该实例会重试1次,更新实例会重试1次。

所以hystrix的超时时间要大于 (1 + MaxAutoRetries + MaxAutoRetriesNextServer) * ReadTimeout 比较好,具体看需求进行配置。

Hystrix 配置

全局配置

  1. #全局设置超时时间
  2. hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
  3. #关闭 Hystrix 功能
  4. #feign.hystrix.enabled=false
  5. #关闭熔断功能
  6. #hystrix.command.default.execution.timeout.enabled=false

禁用 Hystrix

全局关闭 Hystrix

  1. #关闭 Hystrix 功能
  2. feign.hystrix.enabled=false

针对某个客户端关闭 Hystrix ,通过使用 @Scope(“prototype”) 注解为指定的客户端配置 Feign.Builder 实例

构建一个关闭 Hystrix 的配置类

  1. @Configuration
  2. public class DisableHystrixConfiguration {
  3. @Bean
  4. @Scope("prototype")
  5. public Feign.Builder feignBuilder(){
  6. return Feign.builder();
  7. }
  8. }

Hello-Service 的 @FeignClient 注解中,通过 configuration 参数引入上面实例的配置

  1. @FeignClient(value = "SERIVCE-USER",configuration = DisableHystrixConfiguration.class)
  2. @Service
  3. public interface HelloService {
  4. ···
  5. }

指定命令配置

针对尝试机制中对 /hello 接口的熔断时间的配置可通过如下配置

  1. hystrix.command.hello.execution.isolation.thread.timeoutInMilliseconds=5000

服务降级配置

还原之前的类

对 feign-consumer 工程进行改造,添加回之前的HelloService、User类,不使用继承特性实现服务的降级。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pgvlH2ZX-1600188406576)(media/1546481152661.png)]

编写服务降级类

  1. package com.controller;
  2. import org.springframework.stereotype.Component;
  3. import org.springframework.web.bind.annotation.RequestBody;
  4. import org.springframework.web.bind.annotation.RequestHeader;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. @Component
  7. public class HelloServiceFallBack implements HelloService {
  8. @Override
  9. public String hello() {
  10. return "error";
  11. }
  12. @Override
  13. public String hello(@RequestParam("name") String name) {
  14. return "error";
  15. }
  16. @Override
  17. public User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age) {
  18. return new User("未知", 0);
  19. }
  20. @Override
  21. public String hello(@RequestBody User user) {
  22. return "error";
  23. }
  24. }

绑定服务降级类

在服务绑定接口 HelloService 中,通过 @FeignClient 注解的 fallback 属性来指定对应的服务降级实现类

  1. package com.controller;
  2. import org.springframework.cloud.netflix.feign.FeignClient;
  3. import org.springframework.web.bind.annotation.*;
  4. @FeignClient(name="HELLO-SERVICE", fallback = HelloServiceFallBack.class)
  5. public interface HelloService {
  6. ......
  7. }

测试

访问http://localhost:9000/feign-consumer2,有时候会得到如下结果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uWA7AhqM-1600188406577)(media/1546481338539.png)]

注意

在fallback的实现函数中不再支持com.netfix.hystrix.HystrixComand和rx.Observable类型的异步执行方式和响应式执行方式。

其他配置

请求压缩

Spring Cloud Feign支持对请求和响应进行GZIP压缩,以提高通信效率,配置方式如下:

  1. # 配置请求GZIP压缩
  2. feign.compression.request.enabled=true
  3. # 配置响应GZIP压缩
  4. feign.compression.response.enabled=true
  5. # 配置压缩支持的MIME TYPE
  6. feign.compression.request.mime-types=text/xml,application/xml,application/json
  7. # 配置压缩数据大小的下限
  8. feign.compression.request.min-request-size=2048

日志配置

每一个被创建的Feign客户端都会有一个logger。该logger默认的名称为Feign客户端对应的接口的全限定名。Feign日志记录只能响应DEBUG日志级别。

配置属性文件

具体配置在application.properties中配置:

logging.level.=DEBUG开启指定Feign客户端的DEBUG模式日志;为Feign客户端定义接口的完整路径,如下:

  1. # feign日志配置
  2. logging.level.com.controller.HelloService=DEBUG

配置feign-consumer 启动类或实现配置类

  1. package com;
  2. import feign.Logger;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  6. import org.springframework.cloud.netflix.feign.EnableFeignClients;
  7. import org.springframework.context.annotation.Bean;
  8. @EnableFeignClients
  9. @EnableDiscoveryClient
  10. @SpringBootApplication
  11. public class Application {
  12. @Bean
  13. Logger.Level feignLoggerLevel() {
  14. return Logger.Level.FULL;
  15. }
  16. public static void main(String[] args) {
  17. SpringApplication.run(Application.class, args);
  18. }
  19. }

也可以通过实现配置类,然后在具体的Feign 客户端来指定配置类以实现是否要调整不同的日志界别

  1. @Configuration
  2. public class FullLogConfiguration {
  3. @Bean
  4. Logger.Level feignLoggerLevel(){
  5. return Logger.Level.FULL;
  6. }
  7. }

测试

调用 http://localhost:9010/feign-consumer

请求详细日志

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Oblsnma7-1600188406577)(media/1546482631072.png)]

发表评论

表情:
评论列表 (有 0 条评论,264人围观)

还没有评论,来说两句吧...

相关阅读