青蛙小白
博客 / 2023/07

Spring 6.1中的新功能:RestClient[译]

2023/07/13 · — 字 · 阅读约 — 分钟 ·
目录

Spring Framework 6.1 M2引入了RestClient,这是一个新的同步HTTP客户端。正如名称所示,RestClient提供了WebClient的fluent API,并结合了RestTemplate的基础设施。

十四年前,在Spring Framework 3.0中引入RestTemplate时,我们很快发现,在一个类似模板的类中公开HTTP的每个能力会导致方法过多。因此,在Spring Framework 5中,我们为响应式的WebClient使用了的fluent API。通过RestClient,我们引入了一个类似于WebClient的HTTP客户端,它使用RestTemplate的消息转换器、请求工厂、拦截器和其他底层组件。

创建一个RestClient

可以使用其中一个静态的create方法创建一个RestClient。也可以使用RestClient::builder获取一个带有进一步选项的构建器,例如指定要使用的HTTP客户端、设置默认的URL、路径变量和请求头,或者注册拦截器和初始化程序(initializers)。

使用RestClient::create(RestTemplate),您可以使用现有RestTemplate的配置来初始化一个RestClient。

Retrieve

让我们创建一个RestClient,使用它来设置一个基本的GET请求,并使用retrieve方法将网站的内容作为字符串检索出来:

RestClient restClient = RestClient.create();

String result = restClient.get()
  .uri("https://example.com")
  .retrieve()
  .body(String.class);
System.out.println(result);

如果您对响应状态码和响应头信息感兴趣,而不仅仅是内容,您可以使用toEntity方法来获取一个ResponseEntity对象:

ResponseEntity<String> result = restClient.get()
  .uri("https://example.com")
  .retrieve()
  .toEntity(String.class);

System.out.println("Response status: " + result.getStatusCode());
System.out.println("Response headers: " + result.getHeaders());
System.out.println("Contents: " + result.getBody());

RestClient还可以使用Jackson在后台将JSON转换为对象。事实上,它可以转换RestTemplate支持的所有类型,因为它使用相同的消息转换器。请注意URI变量的使用,并且将Accept请求设置为JSON。

int id = ...
Pet pet = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id)
  .accept(APPLICATION_JSON)
  .retrieve()
  .body(Pet.class);

Post

进行POST请求同样简单,可以像这样操作:

Pet pet = ...
ResponseEntity<Void> response = restClient.post()
  .uri("https://petclinic.example.com/pets/new")
  .contentType(APPLICATION_JSON)
  .body(pet)
  .retrieve()
  .toBodilessEntity();

错误处理

默认情况下,当RestClient收到4xx5xx状态码时,它会抛出RestClientException的子类异常。可以使用状态处理器来覆盖此行为,如下所示:

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

Exchange

RestClient提供了exchange方法,用于更高级的场景,因为它提供了对底层HTTP请求和响应的访问。当使用exchange方法时,之前提到的状态处理器不会被应用,因为exchange函数已经提供了对完整响应的访问,让您可以执行任何必要的错误处理:

RestClient restClient = RestClient.create();
restClient.get()
    .uri("https://api.example.com/users/{id}", 123)
    .exchangeToMono(response -> {
        if (response.statusCode().is4xxClientError()) {
            // Custom handling for 4xx errors
            return response.bodyToMono(String.class)
                    .flatMap(errorBody -> Mono.error(new CustomRestClientException(errorBody)));
        } else if (response.statusCode().is5xxServerError()) {
            // Custom handling for 5xx errors
            return response.createException().flatMap(Mono::error);
        } else {
            // Successful response
            return response.bodyToMono(String.class);
        }
    })
    .block();

以上代码创建了一个RestClient实例,并设置了一个GET请求,URI中的变量id为123。我们使用exchangeToMono方法来处理响应,并根据不同的状态码执行自定义的错误处理逻辑。在示例中,当收到4xx状态码时,我们将响应体转换为字符串类型,并通过Mono.error抛出自定义的CustomRestClientException异常。当收到5xx状态码时,我们使用createException()创建相应的异常,并通过Mono.error抛出。对于成功的响应,我们将响应体转换为字符串类型。

请注意,以上代码仅为示例,您需要根据您的具体需求进行适当的调整:

Pet result = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id)
  .accept(APPLICATION_JSON)
  .exchange((request, response) -> {
    if (response.getStatusCode().is4xxClientError()) {
      throw new MyCustomRuntimeException(response.getStatusCode(), response.getHeaders());
    }
    else {
      Pet pet = convertResponse(response);
      return pet;
    }
  });

RestClient的支持

RestClient只是Spring Framework 6.1提供的众多功能之一。许多组件已经支持RestClient:您可以通过MockRestServiceServer来测试其用法,或将其用作@HttpExchange接口的后端。

此外,Spring Boot 3.2 M1将包含对RestClient的支持。

原文链接

评论