OpenFeign VS Retrofit(openfeign是什么)
Retrofit是一个安全的HttpClient,它广泛适用于Android和Java 相关的编程。它可以将HTTP API通过声明式的方式写入Java接口中。
OpenFeign是一个声明式的网络服务端。它使得Web服务的客户端编写更加便利,通过接口和注解,构建应用。
(一)Retrofit与OpenFeign使用介绍
Retrofit构建一般的流程如下:
- Java 接口书写方式
public interface GitHubService {
@GET("users/{user}/repos")
Call> listRepos(@Path("user") String user);
}
- Retrofit 对象初始化与接口构建
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(" ")
.build();
GitHubService service = retrofit.create(GitHubService.class);
- 接口使用方式
Call> repos = service.listRepos("octocat");
参考文件:
https://square.github.io/retrofit/
OpenFeign构建一般的流程如下:
OpenFeign一般是基于springcloud进行开发,下述例子描述内容均基于springcloud
@SpringBootApplication
@EnableFeignClients
public 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 getStores();
@RequestMapping(method = RequestMethod.GET, value = "/stores")
Page 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即可。
- 对SSL对支持,相对于OpenFeign,它使用更加便利。
- 由于其更加底层,所以对一些interceptor的编写更加友好,比如说你需要查看Request与Response的结果并计算他们返回的时间情况。
- Retrofit做了很多报文内容的优化。相见https://www.notion.so/Intercept-e35c3a3cc5c9459689525b947f557d93
(三)总结
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/