Retrofit VS OpenFeign

Retrofit VS OpenFeign

转载自:https://zhuanlan.zhihu.com/p/586414669

Retrofit是一个安全的HttpClient,它广泛适用于Android和Java 相关的编程。它可以将HTTP API通过声明式的方式写入Java接口中。

OpenFeign是一个声明式的网络服务端。它使得Web服务的客户端编写更加便利,通过接口和注解,构建应用。

(一)Retrofit与OpenFeign使用介绍

Retrofit构建一般的流程如下:

  • Java 接口书写方式
public interface GitHubService { 
@GET("users/{user}/repos") 
Call<List<Repo>> listRepos(@Path("user") String user);
}
  • Retrofit 对象初始化与接口构建
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build();
GitHubService service = retrofit.create(GitHubService.class);
  • 接口使用方式
Call<List<Repo>> repos = service.listRepos("octocat");

参考文件:https://square.github.io/retrof

OpenFeign构建一般的流程如下:

  • OpenFeign一般是基于springcloud进行开发,下述例子描述内容均基于SpringCloud
@SpringBootApplication
@EnableFeignClientspublic 
class Application { 
public static void main(String[] args) { 
SpringApplication.run(Application.class, args); 
	} 
}
  • StoreClient.java
@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);
}

参考文档:https://cloud.spring.io/spring-cloud-openfeign/reference/html/

demo地址:https://gitee.com/ddmonk/feign-demo

(二)Retrofit VS OpenFeign

从Google也搜索到一些对于两个选型的一些讨论,笔者结合自身开发经验,整理了一些内容。

Retrofit与OpenFeign相似点

两者均是提供type-safe的HttpClient。

都简化了整体接口的实现,自动完成将Json或XML转化为POJO

两者均可以通过简单的配置完成相关服务。

OpenFeign优势
  • 对于Spring boot应用有天然的支持特性。

  • 支持服务发现[Eureka]与客户端负载[Ribbon]

  • 支持Hystrix服务熔断功能

  • 可以动态的配置HttpClient的包,如启动okhttp等。

  • 相比之下,返回的内容直接是POJO,而Retrofit返回Call

Retrofit优势
  • Retrofit对Android应用适配较好。

  • 相比之下,查询参数不需要在URL里面显示书写,只需使用@Query即可。

  • 由于其更加底层,所以对一些interceptor的编写更加友好,比如说你需要查看Request与Response的结果并计算他们返回的时间情况。

  • Retrofit内部做了很多报文内容的优化。

(三)总结

OpenFeign作为Spring Cloud中的一个组件,所以对于Spring Cloud的其他组件支持力度较好,支持Ribbon、Hystrix等,Retrofit相关内容均需自己完成。但是OpenFeign整个框架由于封装的十分完善,整个的灵活度有所欠缺。比如说我要做Url的多路转发等实现比较复杂,且现在只提供Request的Interceptor,相比之下Retrofit在这方面提供更加丰富,只需要实现一个Interceptor即可完成对Request、Response相关的操作。

总结下来,如果是SpringCloud相关项目且有一套较为完善对微服务架构,使用OpenFeign将使你事半功倍。如果你是非Spring项目,或者你的项目中有很多需要在Request请求过程中做一些操作,比如根据Header中的某个字段进行客户端路由、权限配置等,相较于OpenFeign,你的可编程性更强。

参考文件:https://www.javacodemonk.com/retrofit-vs-feign-for-server-side-d7f199c4
https://sylvainleroy.com/2018/04/13/rest-http-client-feign-vs-retrofit-2/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值