微服务深入浅出(5)-- 声明式调用Feign

Feign的使用

Feign采用了声明式的API接口的风格,将Java Http客户端绑定到它的内部,从而调用过程变的简单。

配置文件:

spring:
  application:
    name: eureka-feign-client
server:
  port: 8765
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9001/eureka/

启动类:

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Feign Config:

@Configuration
public class FeignConfig {
    @Bean
    public Retryer feignRetryer() {
        return new Retryer.Default(100, SECONDS.toMillis(1), 5);
    }
}

实现Feign Client接口:

@FeignClient(value = "hi-service", configuration = FeignConfig.class)
public interface EurekaClientFeign {

    @GetMapping(value = "/hi")
    String sayHiFromClientEureka(@RequestParam(value = "name") String name);

}

经过这几个步骤后,就可以完成Feign对Eureka服务的调用了。

FeignClient的配置

默认的配置类为FeignClientsConfiguration,这个类注入了很多Feign相关的配置Bean,包括FeignRetryer.FeignLoggerFactory和FormattingConversionService等。

另外Decoder、Encoder和Contract这三个类没有Bean注入的情况下,会自动注入默认配置Bean,即ResponseEntityDecoder、SpringEncoder和SpringMvcContract。

我们可以重写FeignClientsConfiguration中的Bean,覆盖默认的配置Bean,从而达到自定义配置的目的。

Feign中使用HttpClent和OkHttp

Feign默认使用HttpUrlConnection来实现网络请求,但它还支持其他网络请求框架。只要pom.xml配置上feign-okhttp或者feign-httpclinet的依赖,然后配置文件上配置feign.httpclient.enabled或者feign.okhttp.enabled为true就可以启用了。

总结

1、@EnableFeignClients注解开启FeignClient功能。只有这个注解存在,程序才会开启对@FeignClient注解的包扫描

2、更具Feign的规则实现接口,并在接口上面加@FeignClient注解

3、程序启动后,扫描所有的@FeignClient的注解的类,并将这些信息注入到IOC容器

4、当接口被调用时,通过JDK代理生成巨日的RequestTemplate模板对象

5、根据RequestTemplate生成Http请求的Request对象

6、Request对象交给Client(HttpUrlConnection/HttpClient/OkHttp)处理

7、最后Client被封装到LoadBalanceClient中,结合Ribbon做负载均衡

原文地址:https://www.cnblogs.com/ijavanese/p/9193218.html