欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OpenFeign 简介

程序员文章站 2022-07-15 13:02:38
...

简介

Feign是一个声明式的Web Service客户端。它的出现使开发Web Service客户端变得很简单。使用Feign只需要创建一个接口加上对应的注解,比如:FeignClient注解。Feign有可插拔的注解,包括Feign注解和JAX-RS注解。Feign也支持编码器和解码器,Spring Cloud Open Feign对Feign进行增强支持Spring MVC注解,可以像Spring Web一样使用HttpMessageConverters等。

Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign,可以做到使用HTTP请求访问远程服务,就像调用本地方法一样的,开发者完全感知不到这是在调用远程方法,更感知不到在访问HTTP请求。

功能

  1. 可插拔的注解支持,包括Feign注解和JAX-RS注解。
  2. 支持可插拔的HTTP编码器和解码器(Gson,Jackson,Sax,JAXB,JAX-RS,SOAP)。
  3. 支持Hystrix和它的Fallback。
  4. 支持Ribbon的负载均衡。
  5. 支持HTTP请求和响应的压缩。
  6. 灵活的配置:基于 name 粒度进行配置
  7. 支持多种客户端:JDK URLConnection、apache httpclient、okhttp,ribbon)
  8. 支持日志
  9. 支持错误重试
  10. url支持占位符
  11. 可以不依赖注册中心独立运行

示例

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.List;
import feign.Feign;
import feign.Logger;
import feign.Param;
import feign.RequestLine;
import feign.Response;
import feign.codec.Decoder;
import static feign.Util.ensureClosed;

/**
 * adapted from {@code com.example.retrofit.GitHubClient}
 */
public class GitHubExample { 
  public static void main(String... args) {
    GitHub github = Feign.builder()
        .decoder(new GsonDecoder())
        .logger(new Logger.ErrorLogger())
        .logLevel(Logger.Level.BASIC)
        .target(GitHub.class, "https://api.github.com");

    System.out.println("Let's fetch and print a list of the contributors to this library.");
    List<Contributor> contributors = github.contributors("netflix", "feign");
    for (Contributor contributor : contributors) {
      System.out.println(contributor.login + " (" + contributor.contributions + ")");
    }
  }

  interface GitHub {

    @RequestLine("GET /repos/{owner}/{repo}/contributors")
    List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
  }

  static class Contributor {

    String login;
    int contributions;
  }

  /**
   * Here's how it looks to write a decoder. Note: you can instead use {@code feign-gson}!
   */
  static class GsonDecoder implements Decoder {

    private final Gson gson = new Gson();

    @Override
    public Object decode(Response response, Type type) throws IOException {
      if (void.class == type || response.body() == null) {
        return null;
      }
      Reader reader = response.body().asReader();
      try {
        return gson.fromJson(reader, type);
      } catch (JsonIOException e) {
        if (e.getCause() != null && e.getCause() instanceof IOException) {
          throw IOException.class.cast(e.getCause());
        }
        throw e;
      } finally {
        ensureClosed(reader);
      }
    }
  }

最后

作为一款全功能的 Http 客户端,Feign 非常好用。此外,仅仅不到 2 万行的代码,非常适合新手进行源码剖析的入门款。

相关标签: feign