微服务微服务生态组件之Spring Cloud OpenFeign详解和源码分析

Spring Cloud OpenFeign

概述

Spring Cloud OpenFeign 官网地址* https://spring.io/projects/spring-cloud-openfeign#overview 总体概览介绍,最新版本为3.1.2***

Spring Cloud OpenFeign 文档地址* https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/ 介绍OpenFeign的详细使用***

本篇我们将单独来学习OpenFeign。学习OpenFeign之前我们先来了解Feign,在没有Feign之前Java可以通过HttpClient、OkHttp、HttpURLConnection、RestTemplate、WebClient等来操作Http,而Feign是NetFlix公司开发的声明式、模板化的HTTP客户端,使得使用Http请求远程服务时就像调用本地方法一样的体验,Feign出现使得我们更加便捷、优雅的调用HTTP客户端,Feign支持多种注解例如自带的注解和JAX-RS注解。

到此引出本篇主角OpenFeign也是一个声明式REST客户端,使用JAX-RS或Spring MVC注解,还支持可插拔编码器和解码器,集成Spring Cloud LoadBalancer,在使用Feign时提供一个负载均衡的http客户端。简单的说Spring Cloud OpenFeign是对Feign一个增强,使其支持Spring MVC注解,并与SpringCloud完成整合。

简单使用

大致的步骤为Pom文件加spring-cloud-starter-openfeign启动器依赖、加注解加配置、最后SpringBoot启动类上加启用注解@EnableFeignClients就完成。而Spring MVC注解风格的不同类型请求方法使用示例如下:

@FeignClient("stores")public interface StoreClient {    @RequestMapping(method = RequestMethod.GET, value = "/stores")    List<Store> getStores();    @RequestMapping(method = RequestMethod.GET, value = "/stores")    Page<Store> getStores(Pageable pageable);    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")    Store update(@PathVariable("storeId") Long storeId, Store store);​    @RequestMapping(method = RequestMethod.DELETE, value = "/stores/{storeId:\\d+}")    void delete(@PathVariable Long storeId);}

关于Spring Cloud OpenFeign配置属性的列表详细可查看附录页。而常见的配置属性如下:

feign:    client:        config:            feignName:                connectTimeout: 5000                readTimeout: 5000                loggerLevel: full                errorDecoder: com.example.SimpleErrorDecoder                retryer: com.example.SimpleRetryer                defaultQueryParameters:                    query: queryValue                defaultRequestHeaders:                    header: headerValue                requestInterceptors:                    - com.example.FooRequestInterceptor                    - com.example.BarRequestInterceptor                decode404: false                encoder: com.example.SimpleEncoder                decoder: com.example.SimpleDecoder                contract: com.example.SimpleContract                capabilities:                    - com.example.FooCapability                    - com.example.BarCapability                queryMapEncoder: com.example.SimpleQueryMapEncoder                metrics.enabled: false

契约配置

如果我们项目原来是使用NetFlix的原生Feign注解进行开发,在OpenFeign中可无需修改Feign原生注解,只需进行配置就可以轻易兼容原来代码无需整改。前面文章示例使用OpenFeign声明代码如下

pa
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值