个人语雀:wnhyang
共享语雀:在线知识共享
Github:wnhyang - Overview

REST Clients :: Spring Framework
The Spring Framework provides the following choices for making calls to REST endpoints:
RestClient - synchronous client with a fluent API.WebClient - non-blocking, reactive client with fluent API.RestTemplate - synchronous client with template method API.HTTP Interface - annotated interface with generated, dynamic proxy implementation.RestClient官方描述:RestClient是一个同步HTTP客户端,它供应了一个当代、流畅的API。它供应了对HTTP库的抽象,许可从Java工具到HTTP要求的方便转换,以及从HTTP相应创建工具。
Spring6.1版本新特性。
创建创建RestClient非常大略,可以利用静态create方法,也可以利用builder创建,其供应了非常丰富的定制化选项,要求工厂、转换器、拦截器、默认头、要求初始化器等等,大略易懂。
RestClient defaultClient = RestClient.create();RestClient customClient = RestClient.builder() .requestFactory(new HttpComponentsClientHttpRequestFactory()) .messageConverters(converters -> converters.add(new MyCustomMessageConverter())) .baseUrl("https://example.com") .defaultUriVariables(Map.of("variable", "foo")) .defaultHeader("My-Header", "Foo") .requestInterceptor(myCustomInterceptor) .requestInitializer(myCustomInitializer) .build();
利用
利用RestClient更为大略,要求URL、Header、Body、相应Response接管、非常处理等等相称丰富大略。
String result = customClient.get() .uri("https://example.com/this-url-does-not-exist") .retrieve() .onStatus((code) -> code.value() / 100 == 4, (request, response) -> { throw new RuntimeException(response.getStatusCode() + " " + response.getHeaders()); }) .body(String.class);
WebClient
WebClient是一个无壅塞、相应式的客户端,用于实行HTTP要求。它在5.0中引入,供应了RestTemplate的替代方案,支持同步、异步和流式传输场景。
早在Spring5版本中就已经涌现,创建方法和RestClient差不多,大略示例如下,其他详细内容可参考官网可Java Doc。
WebClient webClient = WebClient.builder().baseUrl("http://localhost:8081").build();
RestTemplate
比较于上面两位这个更是古老,也恰是以更为常见,利用的更多。但是官网明确表示,推举利用RestClient更换RestTemplate,乃至还细心的整理了更换方案,可知官方可能操持着在未来彻底废弃RestTemplate,大概哦。
HTTP Interface
官方描述:Spring Framework许可您利用@HttpExchange方法将HTTP做事定义为Java接口。您可以将这样的接口传递给HttpServiceProxyFactory,以创建一个代理,该代理通过HTTP客户端(如RestClient或WebClient)实行要求。您还可以从@Controller实现用于做事器要求处理的接口。
大略的来讲,可以类比为OpenFeign,利用方法是险些一样的。
这个也是Spring6的特性,最开始官方支持了WebFlux的实现,后来才加入的RestClient和RestTemplate,利用办法如上图。
方法级别的表明有下,是不是和利用OpenFeign时险些一样了,实在不然,@RequestHeader、@RequestBody、@PathVariable、@RequestParam、@CookieValue等等也是支持的。
@GetExchange@PostExchange@PutExchange@DeleteExchange@PatchExchange
小结
可以说在Spring6.1之后再进行REST调用就有更加丰富的选择了,而且更加大略方便。
写在末了拙作艰辛,字句心血,望诸君垂青,多予支持,不胜感激。
个人博客:无奈何杨(wnhyang)
个人语雀:wnhyang
共享语雀:在线知识共享
Github:wnhyang - Overview