Spring Cloud详解(二)Feign核心原理和性能优化

您所在的位置:网站首页 feign的工作原理 Spring Cloud详解(二)Feign核心原理和性能优化

Spring Cloud详解(二)Feign核心原理和性能优化

2023-11-15 02:10| 来源: 网络整理| 查看: 265

1. 简介

Feign是一个http请求调用的轻量级框架,可以以Java接口注解的方式调用Http请求,而不用像Java中通过封装HTTP请求报文的方式直接调用。Feign通过处理注解,将请求模板化,当实际调用的时候,传入参数,根据参数再应用到请求上,进而转化成真正的请求,这种请求相对而言比较直观。 Feign被广泛应用在Spring Cloud 的解决方案中,是学习基于Spring Cloud 微服务架构不可或缺的重要组件。

2. 工作原理

主程序入口添加了@EnableFeignClients注解开启对FeignClient扫描加载处理。根据Feign Client的开发规范,定义接口并加@FeignClient注解。

当程序启动时,会进行包扫描,扫描所有@FeignClients的注解的类,并且讲这些信息注入Spring IOC容器中,当定义的的Feign接口中的方法呗调用时,通过JDK动态代理方式,来生成具体的RequestTemplate。当生成代理时,Feign会为每个接口方法创建一个RequestTemplate,改对象封装可HTTP请求需要的全部信息,如请求参数名,请求方法等信息都是在这个过程中确定的。

然后RequestTemplate生成Request,然后把Request交给Client去处理,这里的Client可以是JDK原生的URLConnection,Apache的HttpClient,也可以是OKhttp,最后Client被封装到LoadBalanceClient类,这个类结合Ribbon负载均衡发起服务之间的调用。

2.1 Phase 1. 基于面向接口的JDK动态代理方式生成实现类

在使用feign 时,会定义对应的接口类,在接口类上使用Http相关的注解,标识HTTP请求参数信息,如下所示:

interface GitHub { @RequestLine("GET /repos/{owner}/{repo}/contributors") List contributors(@Param("owner") String owner, @Param("repo") String repo); } public static class Contributor { String login; int contributions; } public class MyApp { public static void main(String... args) { GitHub github = Feign.builder() .decoder(new GsonDecoder()) .target(GitHub.class, "https://api.github.com"); // Fetch and print a list of the contributors to this library. List contributors = github.contributors("OpenFeign", "feign"); for (Contributor contributor : contributors) { System.out.println(contributor.login + " (" + contributor.contributions + ")"); } } }

在Feign 底层,通过基于面向接口的动态代理方式生成实现类,将请求调用委托到动态代理实现类,基本原理如下所示:

public class ReflectiveFeign extends Feign{ ///省略部分代码 @Override public T newInstance(Target target) { //根据接口类和Contract协议解析方式,解析接口类上的方法和注解,转换成内部的MethodHandler处理方式 Map nameToHandler = targetToHandlersByName.apply(target); Map methodToHandler = new LinkedHashMap(); List defaultMethodHandlers = new LinkedList(); 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); // 基于Proxy.newProxyInstance 为接口类创建动态实现,将所有的请求转换给InvocationHandler 处理。 T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(), new Class[]{target.type()}, handler); for(DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) { defaultMethodHandler.bindTo(proxy); } return proxy; } //省略部分代码 2.2 Phase 2. 根据Contract协议规则,解析接口类的注解信息,解析成内部表现

Feign 定义了转换协议,定义如下:

/** * Defines what annotations and values are valid on interfaces. */ public interface Contract { /** * Called to parse the methods in the class that are linked to HTTP requests. * 传入接口定义,解析成相应的方法内部元数据表示 * @param targetType {@link feign.Target#type() type} of the Feign interface. */ // TODO: break this and correct spelling at some point List parseAndValidatateMetadata(Class targetType); } 2.2.1 基于Spring MVC的协议规范SpringMvcContract

当前Spring Cloud 微服务解决方案中,为了降低学习成本,采用了Spring MVC的部分注解来完成 请求协议解析,也就是说 ,写客户端请求接口和像写服务端代码一样:客户端和服务端可以通过SDK的方式进行约定,客户端只需要引入服务端发布的SDK API,就可以使用面向接口的编码方式对接服务:

当然,目前的Spring MVC的注解并不是可以完全使用的,有一些注解并不支持,如@GetMapping,@PutMapping 等,仅支持使用@RequestMapping 等,另外注解继承性方面也有些问题;具体限制细节,每个版本能会有些出入,可以参考上述的代码实现,比较简单。

2.3 Phase 3.基于RequestBean动态生成Request

根据传入的Bean对象和注解信息,从中提取出相应的值,来构造Http Request 对象:

2.4 Phase 4. 使用Encoder 将Bean转换成 Http报文正文(消息解析和转码逻辑)

Feign 最终会将请求转换成Http 消息发送出去,传入的请求对象最终会解析成消息体,如下所示:

在接口定义上Feign做的比较简单,抽象出了Encoder 和decoder 接口:

public interface Encoder { /** Type literal for {@code Map}, indicating the object to encode is a form. */ Type MAP_STRING_WILDCARD = Util.MAP_STRING_WILDCARD; /** * Converts objects to an appropriate representation in the template. * 将实体对象转换成Http请求的消息正文中 * @param object what to encode as the request body. * @param bodyType the type the object should be encoded as. {@link #MAP_STRING_WILDCARD} * indicates form encoding. * @param template the request template to populate. * @throws EncodeException when encoding failed due to a checked exception. */ void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException; /** * Default implementation of {@code Encoder}. */ class Default implements Encoder { @Override public void encode(Object object, Type bodyType, RequestTemplate template) { if (bodyType == String.class) { template.body(object.toString()); } else if (bodyType == byte[].class) { template.body((byte[]) object, null); } else if (object != null) { throw new EncodeException( format("%s is not a type supported by this encoder.", object.getClass())); } } } } public interface Decoder { /** * Decodes an http response into an object corresponding to its {@link * java.lang.reflect.Method#getGenericReturnType() generic return type}. If you need to wrap * exceptions, please do so via {@link DecodeException}. * 从Response 中提取Http消息正文,通过接口类声明的返回类型,消息自动装配 * @param response the response to decode * @param type {@link java.lang.reflect.Method#getGenericReturnType() generic return type} of * the method corresponding to this {@code response}. * @return instance of {@code type} * @throws IOException will be propagated safely to the caller. * @throws DecodeException when decoding failed due to a checked exception besides IOException. * @throws FeignException when decoding succeeds, but conveys the operation failed. */ Object decode(Response response, Type type) throws IOException, DecodeException, FeignException; /** Default implementation of {@code Decoder}. */ public class Default extends StringDecoder { @Override public Object decode(Response response, Type type) throws IOException { if (response.status() == 404) return Util.emptyValueOf(type); if (response.body() == null) return null; if (byte[].class.equals(type)) { return Util.toByteArray(response.body().asInputStream()); } return super.decode(response, type); } } }

目前Feign 有以下实现:

Encoder/ Decoder 实现说明JacksonEncoder,JacksonDecoder基于 Jackson 格式的持久化转换协议GsonEncoder,GsonDecoder基于Google GSON 格式的持久化转换协议SaxEncoder,SaxDecoder基于XML 格式的Sax 库持久化转换协议JAXBEncoder,JAXBDecoder基于XML 格式的JAXB 库持久化转换协议ResponseEntityEncoder,ResponseEntityDecoderSpring MVC 基于 ResponseEntity< T > 返回格式的转换协议SpringEncoder,SpringDecoder基于Spring MVC HttpMessageConverters 一套机制实现的转换协议 ,应用于Spring Cloud 体系中 2.5 Phase 5. 拦截器负责对请求和返回进行装饰处理

在请求转换的过程中,Feign 抽象出来了拦截器接口,用于用户自定义对请求的操作:

public interface RequestInterceptor { /** * 可以在构造RequestTemplate 请求时,增加或者修改Header, Method, Body 等信息 * Called for every request. Add data using methods on the supplied {@link RequestTemplate}. */ void apply(RequestTemplate template); }

比如,如果希望Http消息传递过程中被压缩,可以定义一个请求拦截器:

public class FeignAcceptGzipEncodingInterceptor extends BaseRequestInterceptor { /** * Creates new instance of {@link FeignAcceptGzipEncodingInterceptor}. * * @param properties the encoding properties */ protected FeignAcceptGzipEncodingInterceptor(FeignClientEncodingProperties properties) { super(properties); } /** * {@inheritDoc} */ @Override public void apply(RequestTemplate template) { // 在Header 头部添加相应的数据信息 addHeader(template, HttpEncoding.ACCEPT_ENCODING_HEADER, HttpEncoding.GZIP_ENCODING, HttpEncoding.DEFLATE_ENCODING); } } 2.6 Phase 6. 日志记录

在发送和接收请求的时候,Feign定义了统一的日志门面来输出日志信息 , 并且将日志的输出定义了四个等级:

级别说明NONE不做任何记录BASIC只记录输出Http 方法名称、请求URL、返回状态码和执行时间HEADERS记录输出Http 方法名称、请求URL、返回状态码和执行时间 和 Header 信息FULL记录Request 和Response的Header,Body和一些请求元数据 public abstract class Logger { protected static String methodTag(String configKey) { return new StringBuilder().append('[').append(configKey.substring(0, configKey.indexOf('('))) .append("] ").toString(); } /** * Override to log requests and responses using your own implementation. Messages will be http * request and response text. * * @param configKey value of {@link Feign#configKey(Class, java.lang.reflect.Method)} * @param format {@link java.util.Formatter format string} * @param args arguments applied to {@code format} */ protected abstract void log(String configKey, String format, Object... args); protected void logRequest(String configKey, Level logLevel, Request request) { log(configKey, "---> %s %s HTTP/1.1", requesthod(), request.url()); if (logLevel.ordinal() >= Level.HEADERS.ordinal()) { for (String field : request.headers().keySet()) { for (String value : valuesOrEmpty(request.headers(), field)) { log(configKey, "%s: %s", field, value); } } int bodyLength = 0; if (request.body() != null) { bodyLength = request.body().length; if (logLevel.ordinal() >= Level.FULL.ordinal()) { String bodyText = request.charset() != null ? new String(request.body(), request.charset()) : null; log(configKey, ""); // CRLF log(configKey, "%s", bodyText != null ? bodyText : "Binary data"); } } log(configKey, "---> END HTTP (%s-byte body)", bodyLength); } } protected void logRetry(String configKey, Level logLevel) { log(configKey, "---> RETRYING"); } protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException { String reason = response.reason() != null && logLevel.compareTo(Level.NONE) > 0 ? " " + response.reason() : ""; int status = response.status(); log(configKey, "


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3