SpringBoot RestTemplate详解

这篇具有很好参考价值的文章主要介绍了SpringBoot RestTemplate详解。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

参考自:http://events.jianshu.io/p/477e7a3179c6

大家都知道在SpringBoot中一般适用RestTemplate来进行远程调用,那么SpringBoot中如何默认配置RestTemplate,以及如何自定义配置自己的RestTemplate,RestTemplate异步请求如何实现等

1、什么是RestTemplate?

  • RestTemplate是Spring提供的进行远程调用客户端
  • RestTemplate提供了很多远程调用的方法,能够大大提高客户端的编写效率。
    调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求

可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式
ClientHttpRequestFactory接口主要提供了三种实现方式

  • 一种是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)创建底层的Http请求连接
  • 一种方式是使用HttpComponentsClientHttpRequestFactory方式,底层使用HttpClient访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息
  • 第三种方式是使用OkHttp3ClientHttpRequestFactory方式,底层使用OkHttp访问远程的Http服务,使用HttpClient可以配置连接池和证书等信息

2、RestTemplate的优缺点

优点:连接池、超时时间设置、支持异步、请求和响应的编解码
缺点:依赖别的spring版块、参数传递不灵活

RestTemplate默认是使用SimpleClientHttpRequestFactory,内部是调用jdk的HttpConnection,默认超时为-1
SpringBoot RestTemplate详解

3、RestTemplate使用httpclient

1)引入依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2) yaml中添加HttpClientConnection连接池的配置

http:
  maxTotal: 100         #最大连接数
  defaultMaxPerRoute: 20  #并发数
  connectTimeout: 1000   #创建连接的最长时间
  connectionRequestTimeout: 500  #从连接池中获取到连接的最长时间
  socketTimeout: 10000 #数据传输的最长时间
  staleConnectionCheckEnabled: true  #提交请求前测试连接是否可用
  validateAfterInactivity: 3000000   #可用空闲连接过期时间,重用空闲连接时会先检查是否空闲时间超过这个时间,如果超过,释放socket重新建立

3)注入RestTemplate

@Configuration
public class RestTemplateConfig {

    /*@Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }*/

    @Value("${http.maxTotal}")
    private Integer maxTotal;

    @Value("${http.defaultMaxPerRoute}")
    private Integer defaultMaxPerRoute;

    @Value("${http.connectTimeout}")
    private Integer connectTimeout;

    @Value("${http.connectionRequestTimeout}")
    private Integer connectionRequestTimeout;

    @Value("${http.socketTimeout}")
    private Integer socketTimeout;

    @Value("${http.staleConnectionCheckEnabled}")
    private boolean staleConnectionCheckEnabled;

    @Value("${http.validateAfterInactivity}")
    private Integer validateAfterInactivity;


    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(httpRequestFactory());
    }

    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(maxTotal); // 最大连接数
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);    //单个路由最大连接数
        connectionManager.setValidateAfterInactivity(validateAfterInactivity); // 最大空间时间

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(socketTimeout)        //服务器返回数据(response)的时间,超过抛出read timeout
                .setConnectTimeout(connectTimeout)      //连接上服务器(握手成功)的时间,超出抛出connect timeout
                .setStaleConnectionCheckEnabled(staleConnectionCheckEnabled) // 提交前检测是否可用
                .setConnectionRequestTimeout(connectionRequestTimeout)//从连接池中获取连接的超时时间,超时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
                .build();

        //headers
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
        headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
        headers.add(new BasicHeader("Accept-Language", "zh-CN"));
        headers.add(new BasicHeader("Connection", "Keep-Alive"));
        headers.add(new BasicHeader("Content-type", "application/json;charset=UTF-8"));

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .setDefaultHeaders(headers)
                // 保持长连接配置,需要在头添加Keep-Alive
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                //重试次数,默认是3次,没有开启
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
                .build();
    }
}

【一些配置解释】

  • 设置请求配置的超时时间:为了防止请求时间过长而引起资源的过渡浪费。如果在超过设置的timeout还没有数据返回,就直接断开连接
  • headers:添加默认的请求头,这里设置了传送的格式为json,语言为中-英等等属性。HttpClientBuilder.create设置请求头到HttpClient,然后在设置保持的时间,重试的次数,注入给httpClient进行封装。

4、RestTemplate使用okhttp

懒得写了:http://events.jianshu.io/p/477e7a3179c6

5、HttpClient和okhttp的使用以及区别

见我的博客:https://blog.csdn.net/hc1285653662/article/details/127001439

6、RestTemplate异步调用

参考:
https://blog.csdn.net/qq_38622452/article/details/81874483
https://blog.csdn.net/Carson073/article/details/108147005

1、通过 AsyncRestTemplate

AsyncRestTemplate是在Spring4.0中对RestTemplate进行扩展产生的新类,通过返回ListenableFuture对象生成回调机制,以达到异步非阻塞发送http请求

缺点:

  • AsyncRestTemplate已经过期
  • AsyncRestTemplate调用服务时,被调用服务不可达的时候,会抛出异常
  • AsyncRestTemplate不能携带traceId
@GetMapping("/sync/hello")
    public String syncHello() {
        AsyncRestTemplate template = new AsyncRestTemplate();
        String url = "http://localhost:8083/sync/hello";//休眠5秒的服务
        //调用完后立即返回(没有阻塞)
        ListenableFuture<ResponseEntity<String>> forEntity = template.getForEntity(url, String.class);
        //异步调用后的回调函数
        forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
            //调用失败
            @Override
            public void onFailure(Throwable ex) {
                log.error("远程调用faliure");
            }
            //调用成功
            @Override
            public void onSuccess(ResponseEntity<String> result) {
                log.info("res---->"+result.getBody());
            }
        });
        log.info("调用结束");
        return "ok";
    }

SpringBoot RestTemplate详解

2、通过 CompletableFuture 进行异步请求

CompletableFuture 学习见我博客:

添加链接描述

  1. 首先需要自自定义一个线程池
@Component
@ConfigurationProperties(prefix = "my.thread")
@Data
public class ThreadPoolConfigProperties {

    private Integer coreSize;

    private Integer maxSize;

    private Integer keepAliveTime;
}


/**
 * @author houChen
 * @date 2021/12/11 10:35
 * @Description:   自定义线程池配置类
 */
@Configuration
public class MyThreadConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties properties){

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                properties.getCoreSize(),
                properties.getMaxSize(),
                properties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        return threadPoolExecutor;
    }
}

2)通过CompletableFuture 发起异步请求

 /**
     * @Description: 通过CompletableFuture异步发起请求
     * @author houChen
     * @date 2022/9/24 20:18
     */
    @GetMapping("/sync/hello1")
    public String syncHello1() {
        CompletableFuture.supplyAsync(() -> {
            String url = "http://localhost:8083/sync/hello";//休眠5秒的服务
            return restTemplate.getForEntity(url, String.class);
        }, threadPoolExecutor)
                .thenAccept(res -> {
                    log.info("res: {}", res.getBody());
                }).exceptionally(e -> {
            log.error("err:{}", e);
            return null;
        });
        return "ok";
    }

请求: http://localhost:8082/sync/hello1
SpringBoot RestTemplate详解

3、通过@async注解来进行异步调用

 @GetMapping("/sync/hello2")
    public String syncHello2() {
        helloWorldService.asyncRequest();
        return "ok";
    }

@Slf4j
@Service
public class HelloWorldService {

    @Autowired
    RestTemplate restTemplate;

    // 指定使用自己定义的线程池中的线程就行调用
    @Async("threadPoolExecutor")
    public void asyncRequest() {
        String url = "http://localhost:8083/sync/hello";//休眠5秒的服务
        String res = restTemplate.getForEntity(url, String.class).getBody();
        log.info("res :{}", res);
    }
}

SpringBoot RestTemplate详解文章来源地址https://www.toymoban.com/news/detail-455524.html

7、总结

到了这里,关于SpringBoot RestTemplate详解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot中RestTemplate的使用备忘

    2-1 引入Maven依赖 2-2 创建 RestTemplate 配置类,设置连接池大小、超时时间、重试机制等等。 4-1 使用示例 4-2 参数传递的几种方式 5-1 使用示例 5-2 参数传递的几种方式 6-1 使用示例 6-2 设置 url 参数,同Get请求 7-1 使用示例,和postForObject()基本相似,返回的是ResponseEntity罢了 7-2 设置

    2024年02月02日
    浏览(33)
  • SpringBoot整合RestTemplate用法讲解(完整详细)

    前言:本篇主要介绍了RestTemplate中的GET,POST,PUT,DELETE、文件上传和文件下载6大常用的功能,每一个方法和每一行代码都进行了详细的讲解,代码都是亲自测试过的,整篇博客写完以后自己也是受益匪浅,于是在这做个技术分享! 目录 一、RestTemplate简介 二、基础配置 2.1、

    2024年02月12日
    浏览(23)
  • springboot使用restTemplate调用webservice接口

    1.首先确定wsdl的http地址,使用postman测试接口是否成功  在浏览器输入webservice地址可以找到相应的请求和响应示例。    如果postman返回了正确的数据,就说明测试成功! 2.接下来代码:

    2024年01月16日
    浏览(52)
  • SpringBoot 使用RestTemplate来调用https接口

    使用RestTemplate来访问第三方https接口,接口类型为POST,返回数据为JSON,需要忽略https证书,因此对RestTemplate 进行配置,通过HttpClient的请求工厂(HttpComponentsClientHttpRequestFactory)进行构建。HttpComponentsClientHttpRequestFactory使用一个信任所有站点的HttpClient就可以解决问题了。 中间

    2024年02月13日
    浏览(42)
  • 【SpringBoot】springboot使用RestTemplate 进行http请求失败自动重试

    我们的服务需要调用别人的接口,由于对方的接口服务不是很稳定,经常超时,于是需要增加一套重试逻辑。这里使用 Spring Retry 的方式来实现。 一、引入POM 二、 修改启动类 在Spring Boot 应用入口启动类,也就是配置类的上面加上 @EnableRetry 注解,表示让重试机制生效。 注意

    2024年02月08日
    浏览(34)
  • SpringBoot 使用 RestTemplate 发送 binary 数据流

    情况说明: 接口A接受到一个数据流,在postman里的传输方式显示如下: 接口A接受到这个数据流之后,需要转发到接口B进行处理。 这里要注意一点是: postman图中的这种方式和MultipartFile流的传输方式不同,MultipartFile流方式,是在body的form表单中进行传输,需要指定一个key,这

    2024年02月12日
    浏览(34)
  • SpringBoot之RestTemplate使用Apache的HttpClient连接池

    SpringBoot自带的RestTemplate是没有使用连接池的,只是SimpleClientHttpRequestFactory实现了ClientHttpRequestFactory、AsyncClientHttpRequestFactory 2个工厂接口,因此每次调用接口都会创建连接和销毁连接,如果是高并发场景下会大大降低性能。因此,我们可以使用Apache的HttpClient连接池。

    2024年02月11日
    浏览(31)
  • 【Spring Cloud系列】- RestTemplate使用详解

    RestTemplate是Spring框架提供用于调用Rest接口的一个应用,它简化了与http服务通信方式。RestTemplate统一Restfull调用的标准,封装HTTP链接,只要需提供URL及返回值类型即可完成调用。相比传统的HttpClient与Okhttp,RestTemplate是一种优雅,简洁调用RESTfull服务的方式。 RestTemplate默认依赖

    2024年02月08日
    浏览(40)
  • SpringBoot中RestTemplate和WebClient的使用区别及优缺点含完整代码

    点击下载《SpringBoot中RestTemplate和WebClient的使用区别及优缺点含完整代码》 本文将深入探讨Spring Boot中RestTemplate和WebClient的用法、区别和优缺点。通过具体的代码示例,我们将详细解释这两种HTTP客户端的使用方法,并分析它们在不同场景下的适用性。 RestTemplate是Spring框架中用

    2024年02月19日
    浏览(32)
  • Spring 教程—REST 客户端详解(WebClient 、RestTemplate、HTTP 接口)

    Spring框架为调用REST端点提供了以下选择: WebClient - 非阻塞、响应式客户端和 fluent API。 RestTemplate - 带有模板方法API的同步客户端。 HTTP 接口 - 注解式接口,并生成动态代理实现。 WebClient  是一个非阻塞的、响应式的客户端,用于执行HTTP请求。它在5.0中引入,提供了  Re

    2024年02月07日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包