java RPC Feign 远程调用

发布时间 2023-10-06 00:38:41作者: havelearned

一、概述

openFeign是要声明式的web服务客户端,或叫做声明式REST客户端,它让编写web服务客户端变得简单。
使用它的步骤:创建一个接口并注解它。它支持spring MVC的注解,spring cloud openFeign整合了hystrix,同时,可以和Eureka和ribbon配合使用,可以实现负载均衡的http客户端。
可以理解为是请求转发(RPC调度)的入口。本章讲述的是2.2.10.RELEASE版本。

二、使用步骤

1、引入spring-cloud-starter-openfeign 依赖。

2、启动类上加上@EnableFeignClients开启Feign的客户端服务

3、定义一个接口,并加上@FeignClient注解,同时,使用REST风格的接口请求服务。
例如:

@FeignClient(value = "provider")

public interface OpenFeignService {

  @RequestMapping("/open")

  public String getName();

@FeignClient(“provider”)中的value值表示的是这个Feign客户端需要请求的微服务名称。这个名称代表了一个微服务或一个微服务组,其实就是spring.application.name的值。Feign客户端通过这个别名去EurekaServer服务端去找到这个别名对应的微服务。

如果你在项目中还使用了ribbon做负载均衡且结合了Eureka,那么,ribbon将去Eureka的服务注册中心拉取注册表,并缓存到本地,并结合负载均衡算法,选取一个物理主机作为服务端。

三、openFeign的使用

1、如果你不喜欢Feign默认的配置,可以使用FeignClientsConfiguration ,这个类能够让我们全面的控制Feign客户端。步骤如下:

a、定义一个类,继承FeignClientsConfiguration 。
b、重写方法。

c、在@FeignClient 中通过configuration属性引入自定义类。
注意:这个配置类不能注册进spring容器,即不需要使用@Component注解。当然,如果重写Feign的配置不想用自定义类,也可以使用配置文件。如果你既使用了配置类,又使用了配置文件,则配置文件生效。

2、如果你想定义多个Feign客户端,想区分他们,可以使用contextId属性。

@FeignClient(name = 'provider',contextId = "AClient",configuration = "FeignConfig.class")


3、熔断机制
OpenFeign 整合了hystrix做熔断处理,包括超时和异常熔断。其中对于超时,OpenFeign提供了两个参数:connectTimeout和readTimeout
connectTimeout:防止由于服务器处理时间过长而阻塞调用者
readTimeout:从建立连接时开始应用,并在返回响应时间过长时触发。
处理方式为:返回错误信息或fallback 其实就是hystrix的那一套机制。
实现步骤:


a、设置开启feign的熔断:feign.hystrix.enable=true
b、创建一个实现feign客户端类的fallback类,并重写方法,重写的方法其实就是针对这个方法的一个fallback处理。
c、在feign客户端类上的@FeignClient注解中用fallback属性引用

上面步骤仅仅针对学习或项目比较小,如果项目比较大,单独为每个feign客户端配置一个fallback类不合理,我们可以将微服务调用方法集中进行统一的fallback控制,这就涉及到工厂模式,使用工厂类。步骤如下:
a、创建工厂类,需要实现FallbackFactory
b、在feign客户端类上的@FeignClient注解中用fallbackFactory属性引用

4、创建客户端
创建客户端,有两种方式:注解和编码
通常我们一般使用注解的方式,即@FeignClient。我们也可以使用编码的方式手动创建Feign的客户端。这涉及到Feign的builder的使用,属于建造者模式。例如:

@Import(FeignClientsConfiguration.class)
class FooController {

  private FooClient fooClient;

  private FooClient adminClient;

  @Autowired

  public FooController(Client client, Encoder encoder, Decoder decoder, Contract contract, MicrometerCapability micrometerCapability) {

    this.fooClient = Feign.builder().client(client)

      .encoder(encoder)

      .decoder(decoder)

      .contract(contract)

      .addCapability(micrometerCapability)

      .requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))

      .target(FooClient.class, "[https://PROD-SVC](https://PROD-SVC)");

    this.adminClient = Feign.builder().client(client)

      .encoder(encoder)

      .decoder(decoder)

      .contract(contract)

      .addCapability(micrometerCapability)

      .requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))

      .target(FooClient.class, "[https://PROD-SVC](https://PROD-SVC)");

  }

}

5、刷新配置@RefreshScope

在项目中,我们的配置信息一般放在配置中心中,常见的配置中心有:Apollo、nacos和spring cloud config

如果由于某些原因,导致配置中心中的配置修改了,但是,我们项目不想重启,这时候,就需要动态配置刷新的功能。在openFeign中,我们可以在配置文件中开启刷新功能:feign.client.refresh-enabled: true

四、使用-截取重要代码

openFeign的配置文件

eureka:

  client:

    serviceUrl:

      defaultZone: [http://localhost:8761/eureka/](http://localhost:8761/eureka/)

  instance:

    hostname: openfeign0-cheng

    lease-expiration-duration-in-seconds: 20  #租赁维持时间 (存活时间,发送心跳刷新)

    lease-renewal-interval-in-seconds: 10  #租赁续订间隔(发送心跳间隔)

ribbon:

  eureka:

    enabled: true

feign:

  hystrix:

    enabled: true

  client:

    refresh-enabled: true

  httpclient:

    connection-timeout: 500
openFeign的客户端

@Component
//@FeignClient(value = "provider",url = "[http://provider:8002](http://provider:8002)")
@FeignClient(value = "provider",fallbackFactory = TestFallbackFactory.class)
public interface OpenFeignService {

  @RequestMapping("/open")

  @LoadBalanced

  public String getName();

}
openFeign的启动类

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

@EnableFeignClients

@EnableEurekaClient

@EnableDiscoveryClient

public class OpenfeignApplication {

  public static void main(String[] args) {

    SpringApplication.run(OpenfeignApplication.class, args);

  }

}

五、总结

1、openFeign是一个HTTP客户端,它融合了springmvc的注解,使之可以用REST风格的映射来请求转发。

2、可以把openFegin理解为是controller层或是service层。可以取代springmvc控制层作为请求映射,亦或是作为service层处理逻辑,只不过这里,openFeign只是做一个请求转发的逻辑操作。

3、openFeign整合了hystrix做熔断处理,同时,可以和ribbon客户端负载均衡、Eureka注册中心配合使用,实现负载均衡的客户端。

4、openFeign有一个很重要的功能:fallback,其实它是hystrix的特性

Feign的性能优化

这里演示优化连接池的配置:

引入HttpClient的支持:

  <!--引入HttpClient依赖-->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
        </dependency>

配置连接池

feign:
  client:
    config:
      default:
        loggerLevel: BASIC  #日志级别
  httpclient:
    enabled: true # 支持httpclient的开关
    max-connections: 200 # 最大连接数
    max-connections-per-route: 50 # 单个路径的最大连接数

总结:

Feign的最佳实践

这种方式其实是一种规范,但是Spring官方不推荐使用,因为耦合度相当高,对MVC注解是不起作用的,自己只能独立再实现一遍。

这个方式会代码冗余,因为某一个订单服务只需要一两个接口,引入的代码过多。。。

实践方式二:

//@EnableFeignClients(defaultConfiguration = DefaultFeignConfiguration.class,basePackages = "cn.itcast.feign.clients")
@EnableFeignClients(defaultConfiguration = DefaultFeignConfiguration.class,clients = UserClient.class)

总结: