> 文档中心 > Feign详解

Feign详解


一、什么是Feign

Feign是一个http客户端,可以帮助我们更便捷的调用HTTP API。
Spring Cloud openfeign对Feign进行了 增强,使其支持Spring MVC注解,另外还整合了Ribbon和Eureka,从而使得Feign的使用更加方便。
Feign可以做到使用 HTTP 请求远程服务时就像调用本地方法一样的体验,开发者完全感知不到这是远程方 法,更感知不到这是个 HTTP 请求。

二、Feign的使用

2.1 单独使用
Feign作为一个http客户端,可以像okhttp那样,进行单独使用。
引入依赖:

<dependency> <groupId>com.netflix.feign</groupId> <artifactId>feign‐core</artifactId> <version>8.18.0</version>  </dependency> <dependency>   <groupId>com.netflix.feign</groupId> <artifactId>feign‐jackson</artifactId> <version>8.18.0</version>    </dependency>

编写远程调用接口

public interface RemoteService {    @Headers({"Content‐Type: application/json","Accept: application/json"})    @RequestLine("GET /order/findOrderByUserId/{userId}")    public Map findOrderByUserId(@Param("userId")Integer id);}

调用接口,进行远程访问:

public class FeignDemo {    public static void main(String[] args) { RemoteService service = Feign.builder()  .encoder(new JacksonEncoder())  .decoder(new JacksonDecoder())  .options(new Request.Options(1000, 3500))  .retryer(new Retryer.Default(5000, 5000, 3))  .target(RemoteService.class, "http://localhost:8020/"); System.out.println(service.findOrderByUserId(1));    }}

简单的一个使用案例,真实项目中单独使用Feign进行调用的场景不多。大多都是在SpringCloud架构中使用Feign。
2.2 与SpringCloud整合

  1. 引入依赖:
<!‐‐ openfeign 远程调用 ‐‐>  <dependency> <groupId>org.springframework.cloud</groupId>  <artifactId>spring‐cloud‐starter‐openfeign</artifactId>   </dependency>
  1. 在消费者的服务启动类上,写@EnableFeignClients注解。
  2. 编写远程调用接口
@FeignClient(value = "mall-order",path = "/order")public interface OrderFeignService {    @RequestMapping("/findOrderByUserId/{userId}")    public R findOrderByUserId(@PathVariable("userId") Integer userId);}
  1. 调用接口,进行远程调用
@RestController  @RequestMapping("/user")   public class UserController {    @Autowired    OrderFeignService orderFeignService;     @RequestMapping(value = "/findOrderByUserId/{id}")      public R findOrderByUserId(@PathVariable("id") Integer id) {//feign调用 R result = orderFeignService.findOrderByUserId(id);  return result;   }    }

三、Feign扩展配置

Feign提供了很多扩展功能,让用户更灵活的使用,具体如下:
3.1 日志配置
前置条件:在yml中配置是"logging.level.feign接口包路径=debug":

logging:  level:    com.tuling.sidecar.consumer.feign: debug

配置日志级别:

//如果加@Configuration注解,则是全局日志配置,如果不加,则是局部Feign调用日志配置public class FeignLogger {    @Bean    public Logger.Level loggerLevel(){ return Logger.Level.FULL;    }}

日志隔离级别有如下几种:
NONE【性能最佳,适用于生产】:不记录任何日志(默认值)。
BASIC【适用于生产环境追踪问题】:仅记录请求方法、URL、响应状态代码以及执行时间。
HEADERS:记录BASIC级别的基础上,记录请求和响应的header。
FULL【比较适用于开发及测试环境定位问题】:记录请求和响应的header、body和元数据。

指定使用日志的接口:
在@FeignClient 注解中指定使用的配置类

@FeignClient(value = "mall-user-consumer-demo",path = "/user",configuration = FeignLogger.class)public interface SidecarFeign {    @GetMapping("hello")    String hello();    @GetMapping("/demo/{id}")    Map demo(@PathVariable("id") Integer id);}

或者直接在yml中配置接口服务的日志级别:

feign:  client:    config:      mall-user-consumer-demo: #对应的服务名 loggerLevel: FULL

3.2 接口权限配置
在Feign发起请求之前,都会先执行RequestInterceptor拦截器。我们可以在拦截器中进行一些操作。例如, 往request的header里添加认证信息。
Feign提供了一个RequestInterceptor接口的实现类BasicAuthRequestInterceptor,可以直接添加Basic认证信息。

@Configurationpublic class FeignLogger {    @Bean    public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){ return new BasicAuthRequestInterceptor("fox","123456");    }}

也可以自定义RequestInterceptor实现类,如:

public class FeignAuthRequestInterceptor implements RequestInterceptor {    @Override    public void apply(RequestTemplate requestTemplate) { String access_token = UuidUtils.generateUuid().toString(); requestTemplate.header("Authorization",access_token);    }}

在Configuration中配置自定义拦截器:

@Configurationpublic class FeignLogger {    @Bean    public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){ return new BasicAuthRequestInterceptor("fox","123456");    }    /**     * 自定义拦截器     */    @Bean    public FeignAuthRequestInterceptor feignAuthRequestInterceptor(){ return new FeignAuthRequestInterceptor();    }}

也可以在yml中配置自定义拦截器:

feign:  client:    config:      mall-user-consumer-demo: #对应的服务名 loggerLevel: FULL requestInterceptors[0]: #配置拦截器   com.tuling.sidecar.consumer.feign.FeignAuthRequestInterceptor

3.3 配置超时时间
通过 Options 可以配置连接超时时间和读取超时时间,Options 的第一个参数是连接的超时时间(ms), 默认值是 2s;第二个是请求处理的超时时间(ms),默认值是 5s。
Feign详解
3.4 配置客户端组件
Feign默认使用jdk提供的URLConnection发送HTTP请求,可以替换成其他组件,如Apache HttpClient、OkHttp。

3.5 GZIP压缩配置
开启压缩可以有效节约网络资源,提升接口性能,我们可以配置 GZIP 来压缩数据。只有当 Feign 的 Http Client 不是 okhttp3 的时候,压缩才会生效。

3.6 编码器解码器配置
Feign 中提供了自定义的编码解码器设置,同时也提供了多种编码器的实现,比如 Gson、Jaxb、Jackson。 我们可以用不同的编码解码器来处理数据的传输。如果你想传输 XML 格式的数据,可以自定义 XML 编码解 码器来实现获取使用官方提供的 Jaxb。

四、Feign与Ribbon比较

Feign详解

Feign详解
区别一目了然,Feign使用起来更方便,调用起来感觉不到是远程调用接口。且SpringCloud Feign集成了Ribbon,包含了客户端负载均衡的功能。