Spring RestTemplate slow response time

2019-07-23 00:27发布

问题:

While trying to POST object using RestTemplate on Spring 3.2 I got average response time 8 seconds

using curl

time curl -X POST -H "Content-Type: application/xml" -T request.xml https://x.y.com:20000/rest

I'm getting approximately 4 sec average time. I can't understand why.

My configuration:

<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
                <value>x.y.z.Request</value>
                <value>x.y.z.Response</value>
                <value>x.y.z.AnotherRequest</value>
                <value>x.y.z.AnotherResponse</value>
            </list>
        </property>
    </bean>


<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"
        scope="prototype">
        <constructor-arg>
            <bean
                class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
                <property name="readTimeout" value="${application.urlReadTimeout}" />
                <property name="connectTimeout" value="${application.urlConnectionTimeout}" />
            </bean>
        </constructor-arg>

        <property name="messageConverters">
            <list>
                <bean
                    class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                    <property name="marshaller" ref="jaxb2Marshaller" />
                    <property name="unmarshaller" ref="jaxb2Marshaller" />
                </bean>
                <bean class="org.springframework.http.converter.FormHttpMessageConverter" />
                <bean
                    class="org.springframework.http.converter.StringHttpMessageConverter" />
            </list>
        </property>
    </bean>

Then I simple autowire it:

    @Autowired
    RestTemplate restTemplate;

public Response getXml(Request request){

    Response response = restTemplate.postForObject(httpUrl,request, Response.class);
}

P.S: as an alternative I tried to parse Request/Response object using JaxB and an send it using org.apache.http.client.HttpClient the average time is around 7 seconds, which is far from being good.

回答1:

it might be a ipv4/6 issue. try

curl -4 -X POST -H "Content-Type: application/xml" -T request.xml https://x.y.com:20000/rest

if it works for you, run your java cmd using the param

-Djava.net.preferIPv4Stack=true