SpringCloud 声明式服务调用OpenFeign Hoxton版本

2023-10-18 02:38

本文主要是介绍SpringCloud 声明式服务调用OpenFeign Hoxton版本,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Spring Cloud OpenFeign简介:Spring Cloud OpenFeign通过自动配置和Spring环境以及其他Spring编程模型习惯用法提供Spring Boot应用程序对OpenFeign的集成。而Feign是一个声明式的Web服务客户端,它使编写Web服务客户端变得更容易。使用Feign需创建一个接口并对其加上注解,它具有包括Feign注解和JAX-RS注解的可插入的注解支持。Feign还支持可插拔编码器和解码器。Spring Cloud增加了对Spring MVC注解的支持,并使用了Spring Web中默认使用的HttpMessageConverters。Spring Cloud集成了Ribbon和Eureka,在使用Feign时提供负载均衡的http客户端。OpenFeign中集成了Ribbon和Hystrix。

本文主要对Spring Cloud OpenFeign的基本使用进行简单总结,其中SpringBoot使用的2.2.2.RELEASE版本,SpringCloud使用的Hoxton.SR1版本。这里将沿用SpringCloud 服务注册与发现Eureka Hoxton版本的eureka-server作为注册中心,eureka-client作为服务生产者,并通过Maven新建一个名为spring-cloud-openfeign的项目。

一、引入依赖

SpringBoot和SpringCloud依赖这里就不列出来了,还需引入以下依赖:

<!-- Spring Cloud Eureka Client 起步依赖 -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- Spring Cloud OpenFeign 起步依赖 -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- SpringRetry 重试框架依赖 -->
<dependency><groupId>org.springframework.retry</groupId><artifactId>spring-retry</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

二、主启动类

package com.rtxtitanv;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;/*** @author rtxtitanv* @version 1.0.0* @name com.rtxtitanv.OpenFeignApplication* @description 主启动类* @date 2020/2/20 17:54*/
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class OpenFeignApplication {public static void main(String[] args) {SpringApplication.run(OpenFeignApplication.class, args);}
}

@EnableFeignClients:启用feign客户端,不配置包路径就默认扫描主启动类所在包及其子包下的@FeignClient注解,注册feign客户端。

三、编写配置文件

application.yml中进行如下配置:

server:port: ${PORT:9200}spring:application:name: openfeigncloud:loadbalancer:retry:# 开启重试机制enabled: trueeureka:client:# 服务注册,是否将服务注册到Eureka注册中心,true:注册,false:不注册register-with-eureka: true# 服务发现,是否从Eureka注册中心获取注册信息,true:获取,false:不获取fetch-registry: true# 配置Eureka注册中心即Eureka服务端的地址,集群地址以,隔开service-url:defaultZone: http://rtxtitanv:rtxtitanv@eureka-server-01:8001/eureka/,http://rtxtitanv:rtxtitanv@eureka-server-02:8002/eureka/,http://rtxtitanv:rtxtitanv@eureka-server-03:8003/eureka/instance:# 将ip地址注册到Eureka注册中心prefer-ip-address: true# 该服务实例在注册中心的唯一实例ID,${spring.cloud.client.ip-address}获取该服务实例ipinstance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}# 该服务实例向注册中心发送心跳间隔,单位秒,默认30秒lease-renewal-interval-in-seconds: 20# Eureka注册中心在删除此实例之前收到最后一次心跳后的等待时间,单位秒,默认90秒lease-expiration-duration-in-seconds: 60# ribbon指定客户端配置
eureka-client:ribbon:# 指定Ribbon负载均衡策略,ribbon自带七种负载均衡策略,RoundRobinRule:轮询,RandomRule:随机# RetryRule:重试,WeightedResponseTimeRule:响应时间加权,BestAvailableRule:最小并发请求# AvailabilityFilteringRule:可用过滤,ZoneAvoidanceRule:区域权重NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule# ribbon全局配置
ribbon:# 处理请求的超时时间,单位ms,默认1000ReadTimeout: 3000# 连接建立的超时时间,单位ms,默认1000ConnectTimeout: 3000# 切换实例的最大重试次数,不包括首次调用,默认0次MaxAutoRetriesNextServer: 1# 对当前实例的最大重试次数,不包括首次调用,默认1次MaxAutoRetries: 1# 是否对所有操作请求都进行重试,true:是,false:否,只针对get请求进行重试# 设置为true时,如果是put或post等写操作,如果服务器接口不能保证幂等性,会产生不好的结果,所以OkToRetryOnAllOperations设置为true需慎用# 默认情况下,get请求无论是连接异常还是读取异常,都会进行重试,非get请求,只有连接异常时,才会进行重试OkToRetryOnAllOperations: false# 对指定Http响应码进行重试retryableStatusCodes: 404,500,502eager-load:# 是否开启ribbon立即加载,true:开启,false:关闭,默认falseenabled: true# 指定需要立即加载的服务名,也就是你需要调用的服务,有多个则用逗号隔开clients: eureka-clienthystrix:command:# hystrix command参数全局配置default:execution:timeout:# 是否启用hystrix超时,true:启用,false:不启用enabled: trueisolation:thread:# hystrix超时时间,需大于ribbon的超时时间,单位ms# hystrix超时时间需大于(MaxAutoRetries+1)(MaxAutoRetriesNextServer+1)(ConnectTimeout+ReadTimeout)timeoutInMilliseconds: 30000feign:hystrix:# 是否启用hystrix,true:启动,false:停用,默认falseenabled: true# GZIP压缩配置,提高通信效率compression:request:# 是否启用请求GZIP压缩,true:启用,false:不启用enabled: true# 压缩支持的MIME TYPEmime-types: text/xml,application/xml,application/json# 压缩数据的最小值min-request-size: 2048response:# 是否启用响应GZIP压缩,true:启用,false:不启用enabled: trueclient:config:# feign全局配置default:# 指定日志级别,none:不记录任何日志,basic:仅记录请求方法、URL、响应状态代码以及执行时间(适合生产环境)# headers:在basic基础上,记录请求和响应的header,full:记录请求和响应的header、body和元数据,默认noneloggerLevel: basic# feign指定客户端配置,即仅对指定调用的服务生效eureka-client:loggerLevel: full# 设置日志级别
logging:level:# 配置为声明式REST服务调用接口所在包com:rtxtitanv:# 这里需要配置为debug,否则feign的日志级别配置不会生效feignclient: debug

四、声明式服务调用接口

package com.rtxtitanv.feignclient;import com.rtxtitanv.fallbacks.OpenFeignClientFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;/*** @author rtxtitanv* @version 1.0.0* @name com.rtxtitanv.feignclient.OpenFeignClient* @description 声明式REST服务调用接口* @date 2020/2/20 18:13*/
@FeignClient(value = "eureka-client", fallback = OpenFeignClientFallback.class)
public interface OpenFeignClient {/*** 声明式REST服务调用接口方法,调用服务eureka-client的/home** @return 调用eureka-client返回的结果*/@GetMapping("/home")String openFeignTest();
}

@FeignClient:声明注解的接口为Feign客户端,这里简单总结一下@FeignClient的属性。
name:指定FeignClient的名称,如果使用了Ribbon,name会作为微服务名,用于服务发现。
value:和name作用一样。
url:一般用于调试,可以直接指定FeignClient调用的地址。
configuration:指定Feign的配置类,该配置类可以自定义Feign的Encoder、Decoder、LogLevel和Contract。
fallback:指定容错处理类,也叫降级类,用于调用远程接口失败或超时时才会调用的对应接口的容错处理,必须实现@FeignClient注解的接口。
fallbackFactory:指定容错处理工厂类,也叫降级工厂类,用于生成容错处理类实例,可以实现每个接口通用的容错逻辑,减少重复代码。
path:定义当前FeignClient的统一前缀,将当前FeignClient接口所有方法中@RequestMapping的value中相同部分路径配置到path中,简化@RequestMapping的写法。
qualifier:指定@Qualifier注解的值,该值是该FeignClient限定词,@Qualifier可以用该值注入FeignClient。
decode404:当发生http 404错误时,如果该属性为true,会调用decoder进行解码,否则抛出FeignException。
primary:是否将伪代理标记为主Bean,默认为true。

五、OpenFeign服务调用

Controller层:

package com.rtxtitanv.controller;import com.rtxtitanv.service.OpenFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author rtxtitanv* @version 1.0.0* @name com.rtxtitanv.controller.OpenFeignController* @description OpenFeignController* @date 2020/2/20 18:13*/
@RestController
public class OpenFeignController {@Autowiredprivate OpenFeignService openFeignService;@GetMapping("/openfeign")public String openFeign() {return openFeignService.openFeign();}
}

Service层:

package com.rtxtitanv.service;/*** @author rtxtitanv* @version 1.0.0* @name com.rtxtitanv.service.OpenFeignService* @description OpenFeignService* @date 2020/2/20 18:14*/
public interface OpenFeignService {/*** openfeign声明式REST服务调用测试,调用服务eureka-client的/home** @return 调用eureka-client返回的结果*/String openFeign();
}
package com.rtxtitanv.service.impl;import com.rtxtitanv.feignclient.OpenFeignClient;
import com.rtxtitanv.service.OpenFeignService;
import org.springframework.stereotype.Service;import javax.annotation.Resource;/*** @author rtxtitanv* @version 1.0.0* @name com.rtxtitanv.service.impl.OpenFeignServiceImpl* @description OpenFeignService实现类* @date 2020/2/20 18:18*/
@Service
public class OpenFeignServiceImpl implements OpenFeignService {@Resourceprivate OpenFeignClient openFeignClient;@Overridepublic String openFeign() {return openFeignClient.openFeignTest();}
}

IDEA启动eureka-server集群,eureka-client集群和openfeign,其中eureka-client共3个节点,然后不断访问http://localhost:9200/openfeign,这里负载均衡策略设置的轮询策略,根据下面动图中的测试过程和结果,说明以轮询的方式调用eureka-client成功,即成功完成调用eureka-client并使用Ribbon实现负载均衡,负载均衡策略为轮询策略。
测试服务调用结果

六、OpenFeign超时重试

Spring Cloud OpenFeign默认使用的Ribbon实现负载均衡和重试,OpenFeign自己的超时重试机制一般用不上,并且OpenFeign自己的重试默认是关闭的,如果有特殊需求需要用到OpenFeign的重试,可以自己实现OpenFeign的Retryer,然后再注入。这里就总结一下使用Ribbon的超时重试结合Hystrix超时的配置。

先开启Hystrix,配置feign.hystrix.enabled=true,再配置spring.cloud.loadbalancer.retry.enabled=true,开启重试机制,然后配置Ribbon超时重试,以下是全局配置,如果要使用客户端配置,需加一个前缀<client>.<client>为需要调用的服务名。

  • ribbon.ReadTimeout=3000:处理请求的超时时间,单位ms,默认1000。
  • ribbon.ConnectTimeout=3000:连接建立的超时时间,单位ms,默认1000。
  • ribbon.MaxAutoRetries=1:对当前实例的最大重试次数,不包括首次调用,默认1次。
  • ribbon.MaxAutoRetriesNextServer=1:切换实例的最大重试次数,不包括首次调用,默认0次。
  • ribbon.OkToRetryOnAllOperations=false:是否对所有操作请求都进行重试,true表示是,false表示否,只针对get请求进行重试。
  • ribbon.retryableStatusCodes=404,500,502:对指定Http响应码进行重试。

然后再配置Hystrix超时,Hystrix参数配置在配置文件中分为全局配置和实例配置,以command参数为例,全局配置以hystrix.command.default开头,实例配置以hystrix.command.<commandKey>开头,其中<commandKey>默认使用Feign客户端接口中的方法名。这里采用的全局配置,Hystrix超时配置如下:

  • hystrix.command.default.execution.timeout.enable=true:是否启用hystrix超时,true为启用,false为不启用。
  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=30000:hystrix超时时间。

注意:Hystrix超时时间需超过Ribbon的超时时间,否则还没达到Ribbon的超时时间,Hystrix就触发容错保护机制执行降级了,就达不到Ribbon重试的效果,而Ribbon一共请求服务的次数为(MaxAutoRetries+1)(MaxAutoRetriesNextServer+1),所以Hystrix超时时间需要超过(MaxAutoRetries+1)(MaxAutoRetriesNextServer+1)(ConnectTimeout+ReadTimeout)

OpenFeign默认用的Ribbon的重试,以上配置均在配置文件中配置了,这里在服务调用过程中停掉一个eureka-client节点,测试超时重试,测试过程和结果见下面动图:
测试超时重试结果1
这里在服务调用过程中停掉两个eureka-client节点,测试超时重试,测试过程和结果见下面动图:
测试超时重试结果2
分别将ribbon.MaxAutoRetriesNextServer=1改为0和2测试,改为0后,停掉一个eureka-client节点后不会切换节点,调用会失败,改为2后,对应的Hystrix超时时间再调大一点,停掉两个eureka-client节点后会重试切换两次节点而调用成功,笔者已经测试过了,这里就不上结果了,综合上述结果,说明OpenFeign成功使用Ribbon实现超时重试,有兴趣可以自己测试一下。

七、OpenFeign中使用Hystrix降级

OpenFeign中要使用Hystrix,需先配置feign.hystrix.enabled=true开启Hystrix,上文配置文件中已经配置了。然后在OpenFeignClient接口的@FeignClient注解上添加fallback = OpenFeignClientFallback.class指定降级类,OpenFeignClientFallback为OpenFeignClient的降级类,需要实现OpenFeignClient接口,降级类如下:

package com.rtxtitanv.fallbacks;import com.rtxtitanv.feignclient.OpenFeignClient;
import org.springframework.stereotype.Component;/*** @author rtxtitanv* @version 1.0.0* @name com.rtxtitanv.fallbacks.OpenFeignClientImpl* @description OpenFeignClient的降级类* @date 2020/2/20 18:19*/
@Component
public class OpenFeignClientFallback implements OpenFeignClient {@Overridepublic String openFeignTest() {return "home fall back";}
}

停掉eureka-client所有节点,测试服务降级类,根据下面动图中的测试过程和结果,说明服务调用失败时降级成功。
测试服务降级类
也可以在OpenFeignClient接口的@FeignClient注解上添加fallbackFactory = OpenFeignClientFallbackFactory.class指定降级工厂类,注意fallbackFactoryfallback不能共存,OpenFeignClientFallbackFactory为OpenFeignClient的降级工厂类,需要实现FallbackFactory<OpenFeignClient>接口,降级工厂类如下:

package com.rtxtitanv.fallbacks;import com.rtxtitanv.feignclient.OpenFeignClient;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;/*** @author rtxtitanv* @version 1.0.0* @name com.rtxtitanv.fallbacks.OpenFeignClientFallbackFactory* @description OpenFeignClient的降级工厂类* @date 2020/2/20 20:46*/
@Component
public class OpenFeignClientFallbackFactory implements FallbackFactory<OpenFeignClient> {@Overridepublic OpenFeignClient create(Throwable throwable) {return () -> "home fallback reason was: " + throwable.getMessage();}
}

停掉eureka-client所有节点,@FeignClient中的fallback暂时改为fallbackFactory以测试服务降级工厂类,根据下面动图中的测试过程和结果,说明服务调用失败时降级成功。
测试服务降级工厂类

八、OpenFeign日志级别

这里简单总结一下配置文件方式全局配置feign的日志级别,当然除了使用配置文件外还可以使用配置类的方式,不过配置文件方式更简单,优先级更高。这里就总结一下配置文件方式,首先,Feign的日志级别如下:

  • none:不记录任何日志(默认值)。
  • basic:仅记录请求方法、URL、响应状态代码以及执行时间(适合生产环境)。
  • headers:在basic基础上,记录请求和响应的header。
  • full:记录请求和响应的header、body和元数据。

配置文件方式局部配置

feign.client.config.服务名.loggerLevel=日志级别
logging.level.com.rtxtitanv.feignclient.OpenFeignClient=debug

com.rtxtitanv.feignclient.OpenFeignClient为FeignClient接口全限定名。

配置文件方式全局配置

feign.client.config.default.loggerLevel=日志级别
logging.level.com.rtxtitanv.feignclient=debug

com.rtxtitanv.feignclient为FeignClient接口所在包。

具体的配置上文配置文件中已经配置过了,下面是Feign服务调用时控制台打印的日志:

2020-02-22 23:17:09.784 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] ---> GET http://eureka-client/home HTTP/1.1
2020-02-22 23:17:09.784 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] Accept-Encoding: gzip
2020-02-22 23:17:09.784 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] Accept-Encoding: deflate
2020-02-22 23:17:09.784 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] ---> END HTTP (0-byte body)
2020-02-22 23:17:09.791 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] <--- HTTP/1.1 200 (6ms)
2020-02-22 23:17:09.791 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] connection: keep-alive
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] content-length: 22
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] content-type: text/plain;charset=UTF-8
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] date: Sat, 22 Feb 2020 15:17:09 GMT
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] keep-alive: timeout=60
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] 
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] ip:10.0.0.11,port:9001
2020-02-22 23:17:09.792 DEBUG 1280 --- [eureka-client-4] c.rtxtitanv.feignclient.OpenFeignClient  : [OpenFeignClient#openFeignTest] <--- END HTTP (22-byte body)

代码示例

  • Github:https://github.com/RtxTitanV/springcloud-learning/tree/master/springcloud-hoxton-learning/spring-cloud-openfeign
  • Gitee:https://gitee.com/RtxTitanV/springcloud-learning/tree/master/springcloud-hoxton-learning/spring-cloud-openfeign

这篇关于SpringCloud 声明式服务调用OpenFeign Hoxton版本的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/229631

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav