Spring Boot 3.2:将 RestTemplate 替换为 RestClient

1,176 阅读3分钟

Spring Boot 3.2 教程探讨了基于 WebClient 构建的名为 RestClient 的附加功能,这是一种更直观、更现代的使用 RESTful 服务的方法。

在Spring Boot的世界里,向外部服务发出HTTP请求是一项常见的任务。传统上,开发人员依赖RestTemplate来实现这一目的。然而,随着Spring Framework的发展,出现了一种新的、更强大的处理HTTP请求的方法:WebClient。在Spring Boot 3.2中,一个名为RestClient的新添加构建在WebClient之上,为消费RESTful服务提供了一种更直观、更现代的方法。

RestTemplate 的起源

RestTemplate多年来一直是Spring生态系统中的主要内容。它是一个用于发出HTTP请求和处理响应的同步客户端。有了RestTemplate,开发人员可以使用熟悉的Java语法轻松地与RESTful API交互。然而,随着应用程序变得更加异步和无阻塞,RestTemplate的局限性开始变得明显。

以下是使用RestTemplate从外部API获取数据的基本示例:

var restTemplate = new RestTemplate();
var response = restTemplate.getForObject("https://api.example.com/data", String.class);
System.out.println(response);

WebClient 简介

随着Spring WebFlux(一种异步、无阻塞的web框架)的出现,WebClient被引入作为RestTemplate的现代替代方案。WebClient采用反应式原理,非常适合构建反应式应用程序。它提供了对同步和异步通信的支持,以及用于编写请求的流畅的API。

以下是如何使用WebClient来实现相同的HTTP请求:

var webClient = WebClient.create();
var response = webClient.get()
                .uri("https://api.example.com/data")
                .retrieve()
                .bodyToMono(String.class);

response.subscribe(System.out::println);

在 Spring Boot 3.2 中输入 RestClient

Spring Boot 3.2引入了RestClient,这是一个建立在WebClient之上的更高级抽象。RestClient通过提供更直观流畅的API并减少样板文件代码,进一步简化了HTTP请求的生成过程。它保留了WebClient的所有功能,同时提供了一个对开发人员更友好的界面。

让我们来看看如何使用RestClient:

var response = restClient
        .get()
        .uri(cepURL)
        .retrieve()
        .toEntity(String.class);

System.out.println(response.getBody());

有了RestClient,代码变得更加简洁易读。RestClient在内部处理WebClient实例的创建,消除了设置和管理HTTP客户端的复杂性。

比较 RestClient 和 RestTemplate

让我们通过观察一些常见的场景来比较RestClient和RestTemplate:

RestTemplate:

var response = new RestTemplate();

RestClient:

var response = RestClient.create();

或者我们也可以使用我们的旧RestTemplate:

var myOldRestTemplate = new RestTemplate();            
var response = RestClient.builder(myOldRestTemplate);

GET Request

RestTemplate:

var response = restTemplate.getForObject("https://api.example.com/data", String.class);

RestClient:

var response = restClient
        .get()
        .uri(cepURL)
        .retrieve()
        .toEntity(String.class);

POST Request

RestTemplate:

ResponseEntity<String> response = restTemplate.postForEntity("https://api.example.com/data", request, String.class);

RestClient:

var response = restClient
        .post()
        .uri("https://api.example.com/data")
        .body(request)
        .retrieve()
        .toEntity(String.class);

错误处理

RestTemplate:

try {

  String response = restTemplate.getForObject("https://api.example.com/data", String.class);

} catch (RestClientException ex) {

  // Handle exception

}

RestClient:

String request = restClient.get() 
  .uri("https://api.example.com/this-url-does-not-exist") 
  .retrieve()
  .onStatus(HttpStatusCode::is4xxClientError, (request, response) -> { 
      throw new MyCustomRuntimeException(response.getStatusCode(), response.getHeaders()) 
  })
  .body(String.class);

如这些示例所示,与RestTemplate相比,RestClient提供了一种更精简的HTTP请求生成方法。

Spring 文档为我们提供了许多其他示例

结论

在Spring Boot 3.2中,RestClient作为RestTemplate的现代替代品出现,提供了一种更直观、更简洁的方式来使用RESTful服务。RestClient建立在WebClient之上,它采用响应式原则,同时简化了HTTP请求的处理过程。

开发人员现在可以在其Spring Boot应用程序中与外部API交互时,享受更高的生产力和更干净的代码。建议从RestTemplate过渡到RestClient,以获得更高效且经得起未来考验的代码库。