0


Spring Boot 3.2 新特性之 RestClient

SpringBoot 3.2引入了新的 RestClient 用于http接口调用,采用了 fluent API 的风格,可以进行链式调用。

具体的代码参照 示例项目 https://github.com/qihaiyan/springcamp/tree/master/spring-jdbc-client

一、概述

RestClient 是一个类似于 RestTemplate 的的同步接口调用工具。相比于 RestTemplate 采用的是 template 设计模式,RestClient 采用了 fluent API 风格,简单灵活,易于阅读和维护。

二、引入 RestClient

首先引入 spring-boot-starter-web 依赖。

在 build.gradle 中增加一行代码:

implementation 'org.springframework.boot:spring-boot-starter-web'

对 RestClient 进行配置:

@ConfigurationpublicclassRestClientConfig{publicCloseableHttpClienthttpClient(){Registry<ConnectionSocketFactory> registry =RegistryBuilder.<ConnectionSocketFactory>create().register("http",PlainConnectionSocketFactory.getSocketFactory()).register("https",SSLConnectionSocketFactory.getSocketFactory()).build();PoolingHttpClientConnectionManager poolingConnectionManager =newPoolingHttpClientConnectionManager(registry);

        poolingConnectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(Timeout.ofSeconds(2)).build());
        poolingConnectionManager.setDefaultConnectionConfig(ConnectionConfig.custom().setConnectTimeout(Timeout.ofSeconds(2)).build());// set total amount of connections across all HTTP routes
        poolingConnectionManager.setMaxTotal(200);// set maximum amount of connections for each http route in pool
        poolingConnectionManager.setDefaultMaxPerRoute(200);RequestConfig requestConfig =RequestConfig.custom().setConnectionKeepAlive(TimeValue.ofSeconds(10)).setConnectionRequestTimeout(Timeout.ofSeconds(2)).setResponseTimeout(Timeout.ofSeconds(2)).build();returnHttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(poolingConnectionManager).setKeepAliveStrategy(newDefaultConnectionKeepAliveStrategy()).build();}@Slf4jstaticclassCustomClientHttpRequestInterceptorimplementsClientHttpRequestInterceptor{@Override@NonNullpublicClientHttpResponseintercept(HttpRequest request,@NonNullbyte[] bytes,@NonNullClientHttpRequestExecution execution)throwsIOException{
            log.info("HTTP Method: {}, URI: {}, Headers: {}", request.getMethod(), request.getURI(), request.getHeaders());
            request.getMethod();if(request.getMethod().equals(HttpMethod.POST)){
                log.info("HTTP body: {}",newString(bytes,StandardCharsets.UTF_8));}ClientHttpResponse response = execution.execute(request, bytes);ClientHttpResponse responseWrapper =newBufferingClientHttpResponseWrapper(response);String body =StreamUtils.copyToString(responseWrapper.getBody(),StandardCharsets.UTF_8);
            log.info("RESPONSE body: {}", body);return responseWrapper;}}staticclassBufferingClientHttpResponseWrapperimplementsClientHttpResponse{privatefinalClientHttpResponse response;privatebyte[] body;BufferingClientHttpResponseWrapper(ClientHttpResponse response){this.response = response;}@NonNullpublicHttpStatusCodegetStatusCode()throwsIOException{returnthis.response.getStatusCode();}@NonNullpublicStringgetStatusText()throwsIOException{returnthis.response.getStatusText();}@NonNullpublicHttpHeadersgetHeaders(){returnthis.response.getHeaders();}@NonNullpublicInputStreamgetBody()throwsIOException{if(this.body ==null){this.body =StreamUtils.copyToByteArray(this.response.getBody());}returnnewByteArrayInputStream(this.body);}publicvoidclose(){this.response.close();}}@BeanpublicRestTemplaterestTemplate(RestTemplateBuilder builder){return builder
                .requestFactory(()->newHttpComponentsClientHttpRequestFactory(httpClient())).interceptors(newCustomClientHttpRequestInterceptor()).build();}@BeanpublicRestClientrestClient(RestTemplate restTemplate){returnRestClient.builder(restTemplate).requestFactory(newHttpComponentsClientHttpRequestFactory(httpClient())).build();}}

在配置中我们仍然定义了 RestTemplate ,并使用 RestTemplate 来初始化 RestClient 为的是继续使用 RestTemplate 的日志打印功能 参照 https://github.com/qihaiyan/springcamp/tree/master/spring-rest-template-log

如果不想继续使用RestTemplate,那初始化代码可以改为

RestClient.builder().requestFactory(newHttpComponentsClientHttpRequestFactory(httpClient())).build();

同时我们给 RestClient 配置了 requestFactory ,可以使用长连接调用接口。

三、GET接口调用

调用GET接口返回字符串:

restClient.get().uri("https://httpbin.org/get").retrieve().body(String.class)

调用GET接口对象:

restClient.get().uri("https://httpbin.org/get").retrieve().body(MyData.class);

调用GET接口返回List:

List<String> list = restClient.get().uri("http://someservice/list").retrieve().body(newParameterizedTypeReference<>(){});

四、POST接口调用

MyData postBody =newMyData("test","test RestClient");ResponseEntity<String> respObj = restClient.post().uri("https://httpbin.org/post").contentType(MediaType.APPLICATION_JSON).body(postBody).retrieve().toEntity(String.class);

五、Exchange接口调用

当需要对接口返回结果进行更加精确的控制时,可以采用 Exchange 方法。
例如当接口返回 4xx 时,让 restClient 返回空字符串,否则返回正常结果:

restClient.get().uri("https://httpbin.org/get").accept(MediaType.APPLICATION_JSON).exchange((request, response)->{if(response.getStatusCode().is4xxClientError()){
                        log.info("status 4xx");return"";}else{
                        log.info("response: {}", response);return response;}});

六、错误处理

当接口返回错误时,可以在 onStatus 方法中进行判断并进行对应的操作:

restClient.get().uri("https://httpbin.org/status/404").retrieve().onStatus(status -> status.value()==404,(request, response)->{
                    log.info("status 404");}).toBodilessEntity();

toBodilessEntity 方法是一种忽略接口返回结果的方法,当不需要读取接口返回结果时,可以使用 toBodilessEntity 方法。

标签: spring boot 后端 java

本文转载自: https://blog.csdn.net/haiyan_qi/article/details/134771786
版权归原作者 QiHY 所有, 如有侵权,请联系我们删除。

“Spring Boot 3.2 新特性之 RestClient”的评论:

还没有评论