Openfeign

Openfeign

相关扩展

在 2020 以前的 SpringCloud 采用 Ribbon 作为负载均衡,但是 2020 年之后,SpringCloud 吧 Ribbon 移除了,而是使用自己编写的 LoadBalancer 替代.

因此,如果在没有加入 LoadBalancer 依赖的情况下,使用 RestTemplate 或 OpenFeign 远程调用,就会报错

1.是什么

Feign是一个声明性web服务客户端。它使编写web服务客户端变得更容易。使用Feign创建一个接口并对其进行注释。它具有可插入的注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插拔编码器和解码器。Spring Cloud添加了对Spring MVC注释的支持,以及对使用Spring Web中默认使用的HttpMessageConverter的支持。Spring Cloud集成了Eureka、Spring Cloud CircuitBreaker以及Spring Cloud LoadBalancer,以便在使用Feign时提供负载平衡的http客户端。

在这里插入图片描述

为什么不直接使用LoadBalancer +RestTemplate

feign统一对外暴露可以被调用的接口方法,大大简化和降低了调用客户端的开发量,也即由服务提供者给出调用接口清单,消费者直接通过OpenFeign调用即可

比restTemplate本身就多了一层接口方便管理

OpenFeign也可以集成阿里巴巴Sentinel来提供熔断、降级等功能

默认会有LoadBalancer的负载均衡

2.怎么用

大概逻辑:当应用启动时,Feign 使用 Java 的动态代理机制生成接口的实现。这个过程由 Spring Cloud 集成提供支持Feign 客户端在内部构建了请求的详细信息,并将接口方法调用转换为 HTTP 调用。

加依赖
<!--openfeign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
改配置
业务代码

调用方:

主启动类:

@EnableFeignClients

接口类:

@FeignClient

@FeignClient(name = XXXServiceName)
public interface CmnOpenfeignService {

    @PostMapping(XXXServiceName.ConfigGetCityByNameUrl)
    ApiResult<CityCascadeVo> getCityByNameUrl(@RequestBody CityNameQuery query);
}

3.其他特性

超时重传

新版默认超时60秒 会报错 可以通过配置修改

默认OpenFeign客户端等待60秒钟,但是服务端处理超过规定时间会导致Feign客户端返回报错。

为了避免这样的情况,有时候我们需要设置Feign客户端的超时控制,默认60秒太长或者业务时间太短都不好

yml文件中开启配置:

connectTimeout 连接超时时间

readTimeout 请求处理超时时间

也可以通过配置 配置某个服务的超时时间

默认重试机制是关闭的

配置重试机制:

import feign.Retryer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig
{
    @Bean
    public Retryer myRetryer()
    {
        //return Retryer.NEVER_RETRY; //Feign默认配置是不走重试策略的

        //最大请求次数为3(1+2),初始间隔时间为100ms,重试间最大间隔时间为1s
        return new Retryer.Default(100,1,3);
    }
}
OpenFeign默认HttpClient修改

OpenFeign中http client

如果不做特殊配置,OpenFeign默认使用JDK自带的HttpURLConnection发送HTTP请求,

由于默认HttpURLConnection没有连接池、性能和效率比较低,如果采用默认,性能上不是最好的,

推荐使用apache client5

依赖:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3</version>
</dependency>
<!-- feign-hc5-->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-hc5</artifactId>
    <version>13.1</version>
</dependency>
#  Apache HttpClient5 配置开启
spring:
  cloud:
    openfeign:
      httpclient:
        hc5:
          enabled: true
请求和响应压缩
  ####Spring Cloud Consul for Service Discovery
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        prefer-ip-address: true #优先使用服务ip进行注册
        service-name: ${spring.application.name}
    openfeign:
      client:
        config:
          default:
          #cloud-payment-service:
            #连接超时时间
                        connectTimeout: 4000
            #读取超时时间
                        readTimeout: 4000
      httpclient:
        hc5:
          enabled: true
      compression:
        request:
          enabled: true
          min-request-size: 2048 #最小触发压缩的大小
          mime-types: text/xml,application/xml,application/json #触发压缩数据类型
        response:
          enabled: true

 
日志打印功能

对Feign接口的调用情况进行监控和输出:

两个都要加

import feign.Logger;
import feign.Retryer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig
{
    @Bean
    public Retryer myRetryer()
    {
        return Retryer.NEVER_RETRY; //默认
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

在这里插入图片描述

### OpenFeign 使用指南及常见问题解决方案 OpenFeign 是一个基于 Java 的声明式 HTTP 客户端,它简化了服务间调用的开发流程。以下是关于 OpenFeign 的使用指南以及常见问题的解决方案。 #### 1. OpenFeign 基本使用 要使用 OpenFeign,首先需要在项目中引入依赖。以下是一个常见的 Maven 配置示例: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> ``` 接下来,在主类或配置类上添加 `@EnableFeignClients` 注解以启用 Feign 功能。例如: ```java @SpringBootApplication @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 定义一个 Feign 接口来调用远程服务: ```java @FeignClient(name = "example-service", url = "http://example.com") public interface ExampleServiceClient { @GetMapping("/api/resource") String getResource(); } ``` #### 2. 常见问题及解决方案 ##### (1) 中文乱码问题 如果在使用 OpenFeign 调用时遇到中文乱码问题,通常是因为编码设置不正确。可以通过以下方式解决: - 确保请求头中包含正确的编码信息: ```java @Headers("Content-Type: application/json; charset=UTF-8") @PostMapping("/api/resource") String postResource(@RequestBody String body); ``` - 如果使用的是 OkHttp 作为客户端实现,确保引入了正确的依赖[^1]: ```xml <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-okhttp</artifactId> </dependency> ``` ##### (2) 自定义负载均衡策略 默认情况下,OpenFeign 使用 Ribbon 进行负载均衡。如果需要自定义负载均衡策略,可以参考以下方法[^2]: - **方式一:实现 IRule 接口** 通过实现 `IRule` 接口来自定义负载均衡规则。例如,根据服务器性能分配不同权重,或者优先选择同机房实例。 - **方式二:使用 Spring Cloud LoadBalancer** Spring Cloud 提供了更现代化的负载均衡器 `LoadBalancerClient`,可以直接集成到 OpenFeign 中。配置如下: ```yaml spring: cloud: loadbalancer: retry: enabled: true ``` ##### (3) 错误处理 为了更好地处理远程调用中的异常,可以自定义 `ErrorDecoder` 来解析错误响应: ```java @Component public class CustomErrorDecoder implements ErrorDecoder { @Override public Exception decode(String methodKey, Response response) { if (response.status() == 404) { return new ResourceNotFoundException("Resource not found"); } return new FeignException(response.status(), "An error occurred", null, null, null); } } ``` 然后在 Feign 客户端中注入该解码器: ```java @FeignClient(name = "example-service", url = "http://example.com", configuration = CustomFeignConfiguration.class) public interface ExampleServiceClient { // 方法定义 } @Configuration public class CustomFeignConfiguration { @Bean public ErrorDecoder errorDecoder() { return new CustomErrorDecoder(); } } ``` #### 3. 性能优化建议 - **连接池配置**:通过调整 OkHttp 或 Apache HttpClient 的连接池参数,提升并发性能。 - **缓存机制**:对于频繁调用且结果变化不大的接口,可以引入缓存机制减少远程调用次数。 - **超时设置**:合理设置请求超时时间,避免长时间等待影响系统稳定性。 ```yaml feign: client: config: default: connect-timeout: 5000 read-timeout: 5000 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值