spring cloud feign 运用与源码解析

简介

Feign 是一个基于Java的http客户端,采用了声明式API接口的风格,简化并包装了http 客户端,所以在http调用上轻便了很多。

项目搭建

首先,我们启动一个eureka server模块,并且启动两个相同的eureka client实例。
在这里插入图片描述

pom依赖的引入

搭建一个feign模块,需要引入feign的依赖以及eureka client的依赖

<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>

application.properties的编写

对于配置文件没有多大的内容,声明一下eureka client端指定的注册中心。

spring.application.name=eureka-feign
server.port=8081
eureka.client.serviceUrl.defaultZone=http://localhost:1101/eureka/

code的编写

Feign是一个声明式API接口的http client,所以自然要新建一个接口EurekaClientFeign。

# 注解值为要发送请求到子服务的服务名称,fallback的值为消息发送异常的降级处理
@FeignClient(value = "eureka-client", fallback = FeignConfig.class)
public interface EurekaClientFeign {

# 访问eureak-client服务中的/hello/接口
    @GetMapping("/hello/")
    String hello(@RequestParam String name);

在这里贴一下eureka-client 服务中的/hello/请求处理代码

@RestController
@RequestMapping("/hello")
public class DiscoveryController {

    @Value("${server.port}")
    String port;

    @GetMapping("/")
    public String hello(@RequestParam String name) {
        return "Hello, " + name + ",port: " + port;
    }

从代码中可知,接到请求后返回传进的参数和端口。

创建上文中提到的fallback的值FeignConfig类

@Configuration
public class FeignConfig {

    @Bean
    public Retryer feignRetryer(){
        return new Retryer.Default(100, 1000, 5 );
    }
}

这个类主要实现了当请求异常的时候进行的降级处理就是重新发送请求。

接下来写一个Controller去调用就可以了

@RestController
@RequestMapping("/hello")
public class EurekaClientFeignController {

# 注入声明好的feign接口
    @Autowired
    EurekaClientFeign eurekaClientFeign;

# 调用feign接口的声明方法去调用对应的子服务接口
    @GetMapping("/")
    public String hello(@RequestParam String name){
        return eurekaClientFeign.hello(name);
    }
}

启动类的时候只需要添加@EnableFeignClients这个注解就可以了,笔者使用的是spring boot2.0之后的版本,所以不必显示声明@EnableDiscoveryClient注解,已经默认集成到对应的AutoConfiguration里。启动后,访问http://localhost:8081/hello/?name=aa
在这里插入图片描述
并且你刷新或多次访问后,会发现它会轮询的访问两个eureka client 实例,可以猜测feign实现了负载均衡的功能,从之前的fallback对应的类编写,也可猜测feign实现了熔断功能。

源码分析

FeignClient注解分析

首先来分析一下@FeignClient这个注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FeignClient {
    @AliasFor("name")
    String value() default "";

    /** @deprecated */
    @Deprecated
    String serviceId() default "";

    String contextId() default "";

    @AliasFor("value")
    String name() default "";

    String qualifier() default "";

    String url() default "";

    boolean decode404() default false;

    Class<?>[] configuration() default {};

    Class<?> fallback() default void.class;

    Class<?> fallbackFactory() default void.class;

    String path() default "";

    boolean primary() default true;
}

@Target(ElementType.TYPE)修饰,表示FeignClient注解的作用目标在接口上,简单的介绍下各个属性。value(), name()都是一样的,都是定义的serviceId。uri()直接写硬编码的地址,一般用来调试用,decode404()针对返回结果404被解码或者抛异常。configuration()为feign的配置类,默认的配置类为FeignClientsConfiguration,fallback()为相关的熔断类。

FeignClient配置的分析

接下来看下FeignClientsConfiguration,代码太长,就不全贴。需要注意一下带有@Bean
@ConditionalOnMissingBean这两个注解的方法。

@Bean
    @ConditionalOnMissingBean
    public Retryer feignRetryer() {
        return Retryer.NEVER_RETRY;
    }

    @Bean
    @Scope("prototype")
    @ConditionalOnMissingBean
    public Builder feignBuilder(Retryer retryer) {
        return Feign.builder().retryer(retryer);
    }

    @Bean
    @ConditionalOnMissingBean({FeignLoggerFactory.class})
    public FeignLoggerFactory feignLoggerFactory() {
        return new DefaultFeignLoggerFactory(this.logger);
    }

可以知道这个配置类注入了很多个bean,其次@ConditionalOnMissingBean会检测这些bean没有被注入的话,就会默认注入一个bean。之前曾写过的针对falllback的降级类 FeignConfig,不知读者是否还有印象。

@Configuration
public class FeignConfig {

    @Bean
    public Retryer feignRetryer(){
        return new Retryer.Default(100, 1000, 5 );
    }
}

笔者重新实例化一个Retryer的bean去覆盖掉默认的Retryer bean,表明了FeignClientsConfiguration支持自定义配置。

运行原理

主程序上添加@EnableFeignClients这个注解,启动时会自动加载feign的相关配置,并且扫描带有@FeignClient的类,源码在FeignClientsRegistrar类里

// bean的注册
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        this.registerDefaultConfiguration(metadata, registry);
        // feignClients的注册
        this.registerFeignClients(metadata, registry);
    }

// 扫描是否有EnableFeignClients注解,然后加载配置
    private void registerDefaultConfiguration(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        Map<String, Object> defaultAttrs = metadata.getAnnotationAttributes(EnableFeignClients.class.getName(), true);
        if (defaultAttrs != null && defaultAttrs.containsKey("defaultConfiguration")) {
            String name;
            if (metadata.hasEnclosingClass()) {
                name = "default." + metadata.getEnclosingClassName();
            } else {
                name = "default." + metadata.getClassName();
            }

            this.registerClientConfiguration(registry, name, defaultAttrs.get("defaultConfiguration"));
        }

    }

registerFeignClients这个方法扫描所有带有@FeignClient注解的类

private void registerFeignClient(BeanDefinitionRegistry registry, AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
        String className = annotationMetadata.getClassName();
        BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(FeignClientFactoryBean.class);
        this.validate(attributes);
        definition.addPropertyValue("url", this.getUrl(attributes));
        definition.addPropertyValue("path", this.getPath(attributes));
        String name = this.getName(attributes);
        definition.addPropertyValue("name", name);
        String contextId = this.getContextId(attributes);
        definition.addPropertyValue("contextId", contextId);
        definition.addPropertyValue("type", className);
        definition.addPropertyValue("decode404", attributes.get("decode404"));
        definition.addPropertyValue("fallback", attributes.get("fallback"));
        definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
        definition.setAutowireMode(2);
        String alias = contextId + "FeignClient";
        AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
        boolean primary = (Boolean)attributes.get("primary");
        beanDefinition.setPrimary(primary);
        String qualifier = this.getQualifier(attributes);
        if (StringUtils.hasText(qualifier)) {
            alias = qualifier;
        }

        BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className, new String[]{alias});
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
    }

获取到相关的基础配置,最后赋值给BeanDefinitionBuilder,得到BeanDefinition,注入到IOC容器中。之后通过JDK代理,在调用feign client接口方法的时候,就会被拦截,源码在ReflectiveFeign。

public <T> T newInstance(Target<T> target) {
    Map<String, MethodHandler> nameToHandler = targetToHandlersByName.apply(target);
    Map<Method, MethodHandler> methodToHandler = new LinkedHashMap<Method, MethodHandler>();
    List<DefaultMethodHandler> defaultMethodHandlers = new LinkedList<DefaultMethodHandler>();

    for (Method method : target.type().getMethods()) {
      if (method.getDeclaringClass() == Object.class) {
        continue;
      } else if (Util.isDefault(method)) {
        DefaultMethodHandler handler = new DefaultMethodHandler(method);
        defaultMethodHandlers.add(handler);
        methodToHandler.put(method, handler);
      } else {
        methodToHandler.put(method, nameToHandler.get(Feign.configKey(target.type(), method)));
      }
    }
    InvocationHandler handler = factory.create(target, methodToHandler);
    T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(),
        new Class<?>[] {target.type()}, handler);

    for (DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {
      defaultMethodHandler.bindTo(proxy);
    }
    return proxy;
  }

通过jdk代理新建个实例。在SynchronousMethodHandler进行拦截,根据参数生成一个基于http的RequestTemplate对象。

 @Override
  public Object invoke(Object[] argv) throws Throwable {
    RequestTemplate template = buildTemplateFromArgs.create(argv);
    Retryer retryer = this.retryer.clone();
    while (true) {
      try {
        return executeAndDecode(template);
      } catch (RetryableException e) {
        try {
          retryer.continueOrPropagate(e);
        } catch (RetryableException th) {
          Throwable cause = th.getCause();
          if (propagationPolicy == UNWRAP && cause != null) {
            throw cause;
          } else {
            throw th;
          }
        }
        if (logLevel != Logger.Level.NONE) {
          logger.logRetry(metadata.configKey(), logLevel);
        }
        continue;
      }
    }
  }

在上述代码里调用了executeAndDecode()这个方法,这个方法是根据参数生成一个request请求对象,通过http client获取response。

feign 使用的HTTP框架解析

读者都知道feign简化了关于http请求的代码编写,那它内部使用的是哪种HTTP组件呢。
查看下FeignRibbonClientAutoConfiguration这个类

@EnableConfigurationProperties({FeignHttpClientProperties.class})
@Import({HttpClientFeignLoadBalancedConfiguration.class, OkHttpFeignLoadBalancedConfiguration.class, DefaultFeignLoadBalancedConfiguration.class})
public class FeignRibbonClientAutoConfiguration {
    public FeignRibbonClientAutoConfiguration() {
    }

从其import类就可猜测,一种是HttpClient,一个是OkHttp。在观察一下feignRequestOptions这个方法

 @Bean
    @ConditionalOnMissingBean
    public Options feignRequestOptions() {
        return LoadBalancerFeignClient.DEFAULT_OPTIONS;
    }

当缺少feignRequestOptions对应的bean时候,默认注入一个bean。LoadBalancerFeignClient这个类实现Client接口,进入到Client这个接口看下。

 HttpURLConnection convertAndSend(Request request, Options options) throws IOException {
            HttpURLConnection connection = (HttpURLConnection)(new URL(request.url())).openConnection();
            if (connection instanceof HttpsURLConnection) {
                HttpsURLConnection sslCon = (HttpsURLConnection)connection;
                if (this.sslContextFactory != null) {
                    sslCon.setSSLSocketFactory(this.sslContextFactory);
                }

                if (this.hostnameVerifier != null) {
                    sslCon.setHostnameVerifier(this.hostnameVerifier);
                }
            }

其Default内部类中使用的是HttpURLConnection框架,也就是说feign默认的使用是HttpURLConnection,并不是HttpClient以及OkHttp。

feign的负载均衡

查看一下LoadBalancerFeignClient,其中的execute方法。

public Response execute(Request request, Options options) throws IOException {
        try {
            URI asUri = URI.create(request.url());
            String clientName = asUri.getHost();
            URI uriWithoutHost = cleanUrl(request.url(), clientName);
            RibbonRequest ribbonRequest = new RibbonRequest(this.delegate, request, uriWithoutHost);
            IClientConfig requestConfig = this.getClientConfig(options, clientName);
            return ((RibbonResponse)this.lbClient(clientName).executeWithLoadBalancer(ribbonRequest, requestConfig)).toResponse();
        } catch (ClientException var8) {
            IOException io = this.findIOException(var8);
            if (io != null) {
                throw io;
            } else {
                throw new RuntimeException(var8);
            }
        }
    }

代码中执行了executeWithLoadBalancer方法,这个方法里又调用了LoadBalancerCommand类中的submit方法,submit方法又调用了selectServer这个方法

private Observable<Server> selectServer() {
        return Observable.create(new OnSubscribe<Server>() {
            public void call(Subscriber<? super Server> next) {
                try {
                    Server server = LoadBalancerCommand.this.loadBalancerContext.getServerFromLoadBalancer(LoadBalancerCommand.this.loadBalancerURI, LoadBalancerCommand.this.loadBalancerKey);
                    next.onNext(server);
                    next.onCompleted();
                } catch (Exception var3) {
                    next.onError(var3);
                }

            }
        });
    }

由该方法进行选择负载均衡的方法,最终负载均衡交给loadBalancerContext来处理,即之前笔者文章提到过的ribbon。

总结

feign的工作流程总结如下:

  • 主程序启动扫描EnableFeignClients这个注解。
  • 接下来扫描FeignClient注解。
  • 在调用有FeignClient注解标注的接口,开启jdk代理,生成一个requestTemplate对象。
  • 这个request请求交给Client去处理,去判断使用HttpClient,OkHttp 还是默认的HttpURLConnection框架。
  • client类被封装到LoadBalancerClient类里,通过ribbon实现负载均衡。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值