Feign-使用注意项和性能优化点

1. FeignClient注解

FeignClient注解被@Target(ElementType.TYPE)修饰,表示FeignClient注解的作用目标在接口上

@FeignClient(name = "demo-client", url = "https://api.fredia.io", configuration = DemoConfig.class)
public interface DemoClient{
    @RequestMapping(value = "/user/info", method = RequestMethod.GET)
    String searchRepo(@RequestParam("id") String id);
}

2. FeignClient源码

 * Copyright 2013-2016 the original author or authors.

package org.springframework.cloud.netflix.feign;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;

/**
 * Annotation for interfaces declaring that a REST client with that interface should be
 * created (e.g. for autowiring into another component). If ribbon is available it will be
 * used to load balance the backend requests, and the load balancer can be configured
 * using a @RibbonClient with the same name (i.e. value) as the feign client.
 *
 * @author Spencer Gibb
 * @author Venil Noronha
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FeignClient {

    /**
     * The name of the service with optional protocol prefix. Synonym for {@link #name()
     * name}. A name must be specified for all clients, whether or not a url is provided.
     * Can be specified as property key, eg: ${propertyKey}.
     */
    @AliasFor("name")
    String value() default "";

    /**
     * The service id with optional protocol prefix. Synonym for {@link #value() value}.
     *
     * @deprecated use {@link #name() name} instead
     */
    @Deprecated
    String serviceId() default "";

    /**
     * The service id with optional protocol prefix. Synonym for {@link #value() value}.
     */
    @AliasFor("value")
    String name() default "";
    
    /**
     * Sets the @Qualifier value for the feign client.
     */
    String qualifier() default "";

    /**
     * An absolute URL or resolvable hostname (the protocol is optional).
     */
    String url() default "";

    /**
     * Whether 404s should be decoded instead of throwing FeignExceptions
     */
    boolean decode404() default false;

    /**
     * A custom @Configuration for the feign client. Can contain override
     * @Bean definition for the pieces that make up the client, for instance
     * {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}.
     *
     * @see FeignClientsConfiguration for the defaults
     */
    Class[] configuration() default {};

    /**
     * Fallback class for the specified Feign client interface. The fallback class must
     * implement the interface annotated by this annotation and be a valid spring bean.
     */
    Class fallback() default void.class;

    /**
     * Define a fallback factory for the specified Feign client interface. The fallback
     * factory must produce instances of fallback classes that implement the interface
     * annotated by {@link FeignClient}. The fallback factory must be a valid spring
     * bean.
     *
     * @see feign.hystrix.FallbackFactory for details.
     */
    Class fallbackFactory() default void.class;

    /**
     * Path prefix to be used by all method-level mappings. Can be used with or without
     * @RibbonClient.
     */
    String path() default "";

    /**
     * Whether to mark the feign proxy as a primary bean. Defaults to true.
     */
    boolean primary() default true;

}

3. FeignClient分析

声明接口之后,在代码中通过@Resource注入之后即可使用。@FeignClient标签的常用属性如下:

  • name:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现
  • url: url一般用于调试,可以手动指定@FeignClient调用的地址
  • decode404:当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignException
  • configuration: Feign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contract
  • fallback: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口
  • fallbackFactory: 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码
  • path: 定义当前FeignClient的统一前缀

注意:在使用fallback属性时,需要使用@Component注解,保证fallback类被Spring容器扫描到,FeignConfiguration内容如下:


package com.macroflag.plusplatform.auth.server.configuration;

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

import com.macroflag.plusplatform.auth.server.interceptor.ClientTokenInterceptor;

@Configuration
public class DemoConfig{
    @Bean
    ClientTokenInterceptor getClientTokenInterceptor() {
        return new ClientTokenInterceptor();
    }
}

在使用FeignClient时,Spring会按name创建不同的ApplicationContext,通过不同的Context来隔离FeignClient的配置信息,在使用配置类时,不能把配置类放到Spring App Component scan的路径下,否则,配置类会对所有FeignClient生效。

4. Feign Client 和@RequestMapping

当前工程中有和Feign Client中一样的Endpoint时,Feign Client的类上不能用@RequestMapping注解,否则当前工程该endpoint http请求且使用accpet时会报404。

4.1 Controller:

@RestController
@RequestMapping("/demo")
public class demo{
 
    @PostMapping("test1")
    public JsonObject test1() {
    ...
    return jo;
    }
}

4.2 Feign Client

@FeignClient(
        name = "demo",
        url = "http://localhost:8080",
        configuration = DemoConfiguration.class
)
@RequestMapping(value = "/demo")
public interface DemoFeignClient {
 
    @RequestMapping(value = "/test1", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    Info info();
 
}  

如果 @RequestMapping注解被用在FeignClient类上,当像如下代码请求/demo/test1时,注意有Accept header

Content-Type:application/json
Accept:application/json
POST http://localhost:8080/demo/test1

那么会返回 404。

如果不包含Accept header时请求,则是OK:

Content-Type:application/json
POST http://localhost:8080/demo/test1

或者像下面不在Feign Client上使用@RequestMapping注解,请求也是ok,无论是否包含Accept:

@FeignClient(
        name = "demo",
        url = "http://localhost:8080",
        configuration = DemoConfiguration.class
)
public interface DemoFeignClient {
 
    @RequestMapping(value = "/demo/test1", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    Info info();
 
} 

5. Feign请求超时问题

Hystrix默认的超时时间是1秒,如果超过这个时间尚未响应,将会进入fallback代码。而首次请求往往会比较慢(因为Spring的懒加载机制,要实例化一些类),这个响应时间可能就大于1秒了
解决方案有如下三种:

5.1

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
该配置是让Hystrix的超时时间改为5秒

5.2

hystrix.command.default.execution.timeout.enabled: false
该配置,用于禁用Hystrix的超时时间

5.3

feign.hystrix.enabled: false
该配置,用于禁用feign的hystrix。该做法除非一些特殊场景,不推荐使用。

你可能感兴趣的:(Feign-使用注意项和性能优化点)