Spring Boot 3.2 引入了对 RestClient 的支持,这是一个全新的同步 HTTP 客户端,旨在取代广泛使用的 RestTemplate。RestClient 是 Spring Framework 6.1 M2 中引入的,它提供了一个更加现代化和流畅的 API,使得编写 HTTP 客户端代码更加直观和易于阅读。
以下是使用RestClient和RestTemplate实现相同功能的代码示例,包括发送GET、POST请求,以及处理响应和错误等,来看看他们有什么不同。
String result = restClient.get()
.uri("http://example.com/api/articles/{articleId}", articleId)
.retrieve()
.body(String.class);
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/articles/{articleId}";
String response = restTemplate.getForObject(url, String.class, articleId);
Article article = new Article("New Article");
ResponseEntity<Void> response = restClient.post()
.uri("http://example.com/api/articles")
.contentType(MediaType.APPLICATION_JSON)
.body(article, Void.class)
.exchange();
Article article = new Article("New Article");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Article> request = new HttpEntity<>(article, headers);
ResponseEntity<Void> response = restTemplate.postForEntity("http://example.com/api/articles", request);
Article receivedArticle = restClient.get()
.uri("http://example.com/api/articles/{articleId}")
.retrieve()
.bodyToClient(Article.class);
Article receivedArticle = restTemplate.getForObject("http://example.com/api/articles/{articleId}", Article.class);
Article article = restClient.get()
.uri("http://example.com/api/articles/{articleId}")
.retrieve()
.onStatus(HttpStatus::isNotFound, (request, response) -> {
throw new ArticleNotFoundException("Article not found: " + articleId);
})
.body(Article.class);
try {
Article receivedArticle = restTemplate.getForObject("http://example.com/api/articles/{articleId}", Article.class);
} catch (HttpClientErrorException ex) {
if (ex.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new ArticleNotFoundException("Article not found: " + articleId);
}
// 抛出其他异常或处理其他状态码
}
相比于RestTemplate,RestClient有以下几个优点:
不过由于RestClient是一个相对较新的组件,它可能还没有像RestTemplate那样经过广泛的测试和使用。这意味着在某些情况下,RestTemplate可能有更多的社区支持和经验分享。而且使用RestClient可能需要添加额外的依赖项,也需要开发者花费一定的时间来学习。
总的来说,RestClient 在 Spring Boot 3.2 中提供了一个更加现代和高效的方式来处理同步 HTTP 请求,同时保持了与 RestTemplate 的兼容性。这使得开发者可以享受到新的 API 带来的便利,同时也可以逐步迁移现有的代码库。随着 Spring Boot 和 Spring Framework 的不断发展,RestClient 有望成为未来 Spring 应用程序中的标准 HTTP 客户端选择。