当前位置: 代码网 > it编程>编程语言>Java > 在SpringBoot中使用RestTemplate详解

在SpringBoot中使用RestTemplate详解

2025年12月08日 Java 我要评论
springboot中使用resttemplate1、配置文件# 最大连接数http.maxtotal=100# 并发数http.defaultmaxperroute=20# 客户端创建连接超时时间h

springboot中使用resttemplate

1、配置文件

# 最大连接数
http.maxtotal=100

# 并发数
http.defaultmaxperroute=20

# 客户端创建连接超时时间
http.connecttimeout=10000

# 从连接池中获取到连接的最长时间
http.connectionrequesttimeout=500

# 服务端响应超时时间
http.sockettimeout=30000

# 提交请求前测试连接是否可用
http.staleconnectioncheckenabled=true

# 可用空闲连接过期时间,重用空闲连接时会先检查是否空闲时间超过这个时间,如果超过,释放socket重新建立
http.validateafterinactivity=3000000

2、配置类

import org.apache.http.header;
import org.apache.http.client.httpclient;
import org.apache.http.client.config.requestconfig;
import org.apache.http.config.registry;
import org.apache.http.config.registrybuilder;
import org.apache.http.conn.httpclientconnectionmanager;
import org.apache.http.conn.socket.connectionsocketfactory;
import org.apache.http.conn.socket.plainconnectionsocketfactory;
import org.apache.http.conn.ssl.sslconnectionsocketfactory;
import org.apache.http.impl.client.defaultconnectionkeepalivestrategy;
import org.apache.http.impl.client.defaulthttprequestretryhandler;
import org.apache.http.impl.client.httpclientbuilder;
import org.apache.http.impl.conn.poolinghttpclientconnectionmanager;
import org.apache.http.message.basicheader;
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.componentscan;
import org.springframework.context.annotation.configuration;
import org.springframework.context.annotation.propertysource;
import org.springframework.http.client.clienthttprequestfactory;
import org.springframework.http.client.httpcomponentsclienthttprequestfactory;
import org.springframework.web.client.resttemplate;

import java.util.arraylist;
import java.util.list;


@configuration
@componentscan("com.xxx")
@propertysource(value = {"classpath:/xxx.properties", "classpath:/yyy.properties"}, encoding = "utf-8")
public class xxxconfiguration {
    @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;

    /**
     * @description: rest模板
     * @return: org.springframework.web.client.resttemplate
     * @author: wsdhla
     * @date: 2022/06/27 16:34
     */
    @bean
    public resttemplate resttemplate() {
        return new resttemplate(httprequestfactory());
    }

    /**
     * @description: 请求连接池配置
     * @return: org.springframework.http.client.clienthttprequestfactory
     * @author: wsdhla
     * @date: 2022/06/27 16:35
     */
    @bean
    public clienthttprequestfactory httprequestfactory() {
        return new httpcomponentsclienthttprequestfactory(httpclient());
    }

    /**
     * @description: httpclient
     * @return: org.apache.http.client.httpclient
     * @author: wsdhla
     * @date: 2022/06/27 16:42
     */
    @bean
    public httpclient httpclient() {
        requestconfig requestconfig = requestconfig.custom()
                .setsockettimeout(sockettimeout)
                .setconnecttimeout(connecttimeout)
                .setstaleconnectioncheckenabled(staleconnectioncheckenabled)
                .setconnectionrequesttimeout(connectionrequesttimeout)
                .build();


        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(poolinghttpclientconnectionmanager())
                .setdefaultheaders(headers)
                .setkeepalivestrategy(new defaultconnectionkeepalivestrategy())
                .setretryhandler(new defaulthttprequestretryhandler(2, true))
                .build();
    }

    /**
     * @description: http连接管理器
     * @return: org.apache.http.conn.httpclientconnectionmanager
     * @author: wsdhla
     * @date: 2022/06/27 16:41
     */
    @bean
    public httpclientconnectionmanager poolinghttpclientconnectionmanager() {
        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);

        return connectionmanager;
    }
}

3、工具类

import org.springframework.http.httpentity;
import org.springframework.http.httpheaders;
import org.springframework.http.httpmethod;
import org.springframework.http.responseentity;
import org.springframework.stereotype.component;
import org.springframework.web.client.restclientexception;
import org.springframework.web.client.resttemplate;

import javax.annotation.resource;
import java.util.map;


@component
public class resttemplateutils {

    private static resttemplate resttemplate;

    /**
     * post请求调用方式
     * @param url          请求url
     * @param requestbody  请求参数体
     * @param responsetype 返回对象类型
     * @return responseentity 响应对象封装类
     */
    public static <t> responseentity<t> post(string url, object requestbody, class<t> responsetype)
            throws restclientexception {
        return resttemplate.postforentity(url, requestbody, responsetype);
    }

    @resource
    public void setresttemplate(resttemplate resttemplate) {
        resttemplateutils.resttemplate = resttemplate;
    }
}

4、具体使用

httpheaders headers = new httpheaders();
headers.setcontenttype(mediatype.application_json);
headers.add("acc-key", acc-key);

jsonobject requestparam = new jsonobject();
requestparam.put("code", code);
requestparam.put("message", message);

httpentity<string> requestbody = new httpentity<string>(json.tojsonstring(requestparam), headers);

responseentity<实体类> resp = resttemplateutils.post(url, requestbody, 实体类.class);

resttemplate默认使用java自带的httpurlconnection,没有池化,会有性能问题,可以使用httpclient或者okhttp

httpclient示例:

@configuration
public class httpclientextconfig {

    @conditionalonmissingbean(resttemplate.class)
    @bean
    public resttemplate resttemplate() {
        closeablehttpclient httpclient = httpclients.custom()
                .setconnectionmanager(new poolinghttpclientconnectionmanager())
                .build();

        httpcomponentsclienthttprequestfactory requestfactory = new httpcomponentsclienthttprequestfactory();
        requestfactory.sethttpclient(httpclient);

        return new resttemplate();
    }
}
<dependency>
    <groupid>org.apache.httpcomponents</groupid>
    <artifactid>httpclient</artifactid>
    <version>4.5.13</version>
</dependency>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com