springcloud:REST客户端组件Feign的工作原理、整合流程
Feign是一种声明式、模板化的HTTP客户端Spring Cloud将其整合到了Netflix项目下。其主要目的是为了简化web service客户端开发在springcloud体系中负责调用集群服务降低开发量擅长于RPC的调用领域。Feign与eureka、ribbon集成后就具备负载均衡的功能。其对自带注解和第三方注解都支持另外提供编码器和解码器来帮助用户封装请求、解析响应。一、基本操作1、编码器如果需要对请求内容进行处理例如把客户端对象转成JSON、XML等场景则需要使用Feign的编码器2、解码器客户端对服务响应的内容进行处理例如把响应的JSON、XML转成对象3、自定义解码器和编码器如果对编码和解码有特殊要求则可以进行自定义编码器和解码器。实现方法也非常简单编码器实现Encoder的encode方法解码器实现Decoder的decode方法4、自定义Feign客户端Feign通过Client接口发送请求Client有多种实现方式包括httpclient默认使用java.net.HttpURLConnection。我们可以通过实现Feign.Client来自定义Feign客户端逻辑写在execute方法里面。整个过程本质上是一个对象转换过程。5、解析第三方注解Feign支持第三方注解的使用。不过Feign本身不清楚第三方注解的意义需要通过一个翻译器来进行翻译使用方法。一个翻译器需要继承Feign.BaseContract类BaseContract则是实现Contract接口。类如JARSContract这种第三方注解翻译器也是继承了BaseContract。BaseContract有三个级别的注解处理方法一般我们实现方法注解的那个即可。相关步骤5.1 定义新注解5.2 新建Contract类需要继承Contract.BaseContract并实现其处理方法级注解等接口。5.3 把contract传给feign.Client6、请求拦截器Feign支持在发送请求前对发送的模板进行操作。如果要自定义连接器的话则需要实现RequestInterceptor接口实现其apply方法。自定义拦截器的步骤6.1、自定义拦截器实现RequestInterceptor接口。6.2、创建客户端把自定义的拦截器传入reuqestInterceptor方法中拦截器可以有多个。7、接口日志默认情况下 Feign是不记录接口日志的。为了方便了解接口的调用情况使用LogLevel方法来进行配置配置日志输出位置以及级别public static void main(String[] args) { // 获取服务接口 PersonClient personClient Feign.builder() .logLevel(Logger.Level.HEADERS) .logger(new Logger.JavaLogger().appendToFile(logs/feign.log)) .target(PersonClient.class, http://127.0.0.1:8089/); personClient.sayHello(); }二、单独使用Feign1、在pom.xml中引入Feign依赖dependency groupIdio.github.openfeign/groupId artifactIdfeign-core/artifactId version9.5.0/version /dependency dependency groupIdio.github.openfeign/groupId artifactIdfeign-gson/artifactId version9.5.0/version /dependency2、编写服务接口通过Get向服务提供方请求hello服务。public interface HelloClient { RequestLine(GET /hello) String sayHello(); }3、 编写客户端运行类public class HelloMain { public static void main(String[] args) { // 调用Hello接口 HelloClient hello Feign.builder().target(HelloClient.class, http://127.0.0.1:8080/); System.out.println(hello.getClass().getName()); System.out.println(hello.sayHello()); } }Feign利用jdk动态代理机制生成动态代理动态代理实例会封装请求信息然后交给feign.Clint来发送请求。三、Spring Cloud整合Feign1、在pom.xml中引入Feign依赖dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-feign/artifactId /dependency2、在启动类中加入EnableFeignClients注解打开Feign开关SpringBootApplication EnableEurekaClient EnableFeignClients public class InvokerApplication { public static void main(String[] args) { SpringApplication.run(InvokerApplication.class, args); } }3、编写客户端接口接口类前加FeignClient“调用的服务名称”FeignClient(spring-feign-provider) //声明调用的服务名称 public interface PersonClient { RequestMapping(method RequestMethod.GET, value /hello) String hello(); RequestMapping(method RequestMethod.GET, value /person/{personId}) Person getPerson(PathVariable(personId) Integer personId); }