Retrofit vs Feign: 介绍、对比及示例

发布于:2025-05-14 ⋅ 阅读:(12) ⋅ 点赞:(0)

1. 介绍

Retrofit

Retrofit 是 Square 公司开发的一个类型安全的 HTTP 客户端库,主要用于 Android 和 Java 应用。它将 HTTP API 转换为 Java 接口,通过注解来描述 HTTP 请求。

主要特点:

  • 基于注解的 API 定义
  • 支持同步和异步调用
  • 支持多种数据格式转换 (JSON, XML 等)
  • 可与 RxJava、Coroutines 等集成
  • 主要用于移动端开发

Feign

Feign 是 Netflix 开发的一个声明式 Web Service 客户端,后被纳入 Spring Cloud 生态。它使得编写 Web Service 客户端变得更简单。

主要特点:

  • 声明式的 REST 客户端
  • 与 Spring Cloud 深度集成
  • 支持负载均衡 (与 Ribbon 集成)
  • 支持服务发现 (与 Eureka 集成)
  • 主要用于微服务间的调用

2. 对比

特性 Retrofit Feign
开发公司 Square Netflix (现属于 Spring Cloud)
主要使用场景 Android/Java 客户端应用 微服务间调用
注解支持
同步/异步 都支持 主要同步,可通过其他方式实现异步
集成能力 OkHttp, RxJava, Coroutines Ribbon, Hystrix, Eureka
配置复杂度 相对简单 与 Spring Cloud 集成时较复杂
负载均衡 不支持 支持 (通过 Ribbon)
服务发现 不支持 支持 (通过 Eureka)
社区支持 主要面向移动端 主要面向微服务

3. 示例代码

Retrofit 示例

// 1. 定义接口
public interface GitHubService {
    @GET("users/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);
    
    @GET("users/{user}/repos")
    Observable<List<Repo>> listReposRx(@Path("user") String user);
}

// 2. 创建 Retrofit 实例
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build();

// 3. 创建服务实例
GitHubService service = retrofit.create(GitHubService.class);

// 4. 同步调用
Call<List<Repo>> call = service.listRepos("octocat");
Response<List<Repo>> response = call.execute();

// 5. 异步调用
call.enqueue(new Callback<List<Repo>>() {
    @Override
    public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
        // 处理响应
    }
    
    @Override
    public void onFailure(Call<List<Repo>> call, Throwable t) {
        // 处理错误
    }
});

// 6. RxJava 方式调用
service.listReposRx("octocat")
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(repos -> {
        // 处理结果
    }, throwable -> {
        // 处理错误
    });

Feign 示例

// 1. 添加依赖 (Spring Cloud OpenFeign)
// 在Spring Boot应用中

// 2. 启用Feign客户端
@SpringBootApplication
@EnableFeignClients
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

// 3. 定义Feign客户端接口
@FeignClient(name = "github-client", url = "https://api.github.com")
public interface GitHubClient {
    @GetMapping("/users/{user}/repos")
    List<Repo> listRepos(@PathVariable("user") String user);
    
    // 带负载均衡的示例 (需要服务注册中心)
    @FeignClient(name = "user-service") // 从注册中心获取服务实例
    @GetMapping("/api/users/{id}")
    User getUserById(@PathVariable("id") Long id);
}

// 4. 在Controller或Service中使用
@RestController
public class MyController {
    private final GitHubClient gitHubClient;
    
    public MyController(GitHubClient gitHubClient) {
        this.gitHubClient = gitHubClient;
    }
    
    @GetMapping("/repos/{user}")
    public List<Repo> getRepos(@PathVariable String user) {
        return gitHubClient.listRepos(user);
    }
}

// 5. 配置示例 (application.yml)
feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
        loggerLevel: basic
  hystrix:
    enabled: true # 启用熔断

4. 如何选择

  • 选择 Retrofit 当:

    • 开发 Android 应用
    • 需要与 RxJava 或 Coroutines 集成
    • 调用第三方 API 而非自己的微服务
    • 需要更轻量级的解决方案
  • 选择 Feign 当:

    • 开发 Spring Cloud 微服务
    • 需要服务发现和负载均衡
    • 需要与 Hystrix 熔断器集成
    • 在服务间进行 REST 调用

两者都是优秀的 HTTP 客户端库,选择取决于具体的使用场景和技术栈。

如果需要更复杂的微服务功能(如负载均衡、服务发现),Feign 仍是更好的选择,但 Retrofit 在客户端场景下的简洁性和性能表现更胜一筹。