Spring Boot 3.2:将 RestTemplate 替换为 RestClient
在Spring Boot 3.2中,RestTemplate
已经不再推荐使用,因为它不支持非阻塞IO,不支持响应式流,并且可能在未来的版本中被移除。因此,推荐使用 WebClient
作为替代方案。
以下是如何使用 WebClient
发送HTTP请求的示例代码:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
@RestController
public class MyRestController {
private WebClient webClient = WebClient.create("http://example.com");
@GetMapping("/getData")
public Mono<String> getData() {
return webClient.get()
.uri("/api/data")
.retrieve()
.bodyToMono(String.class);
}
}
在这个例子中,我们创建了一个 WebClient
实例,用于向 http://example.com/api/data
发送GET请求,并期望返回一个字符串。这是一个响应式的例子,适用于非阻塞IO的场景。
评论已关闭