This is the 19th day of my participation in the First Challenge 2022.

RestTemplate is used to access RESTful interfaces of HTTP endpoints. SpringBoot provides quick and easy use and supports custom configuration of connection parameters.

RestTemplate is SpringBoot used to access the RESTful services client class template tool, located in the org. Springframework. Web. The client package.

1. Introduce the RestTemplate

1.1 Manual Creation

To create a RestTemplate object, you can use the same method to create a new instance object, but the instance object under this method is not managed by the Spring container and does not function as the Spring framework does.

RestTemplate restTemplate = new RestTemplate()
Copy the code

1.2 Annotation Injection

SpringBoot has the RestTemlate class built in and managed by the container, so the restTemplate object can be used by annotation injection for classes that are also managed by the container.

@Autowried
private RestTemplate restTemplate;
Copy the code

1.3 Could not autowire. No beans of ‘RestTemplate’ type found

If you use the injected restTemplate object directly, the above message is displayed, And prompt Consider defining a bean of type ‘org. Springframework. Web. Client. RestTemplate’ in your configuration.

The reason for this problem is that the RestTemplate is not defined, that is, the object is not instantiated, and the bean object cannot be found in the container when it is used. In this case, you only need to define the configuration class for the object to be added to the container.

@Configuration
public class Config {
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        returnbuilder.build(); }}Copy the code

Note that:

  • Before SpringBoot1.3, you do not need to manually configure the RestTemplate to be added to the container. SpringBoot automatically defines the RestTemplate and injects it into the container
  • After SpringBoot1.4, SpringBoot no longer defines a custom RestTemplate injection. Instead, SpringBoot defines a RestTemplateBuilder, requiring the user to further define the RestTemplate
    • The build() method of the RestTemplateBuilder object is, in essence, usednew RestTemplate()To create the restTemplate object

2. Customize the RestTemplate configuration

SpringBoot provides default values for RestTemplate parameters, so you can use them as little as possible. Of course, you can customize the configuration of RestTemplate generation as required.

2.1 Define the HTTP client factory class

The client factory class allows you to define the connection pool to use in restTemplate connections, the maximum number of connections allowed, connection timeout, and so on.

RestTemplate is a request utility class packaged by SpringBoot, which uses HttpClient. Therefore, we need to import the HttpClient dependency information when we operate on the RestTemplate HTTP client factory.

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>
Copy the code

Set HTTP connection pool parameters

@Bean
public HttpClientConnectionManager poolingConnectionManager(a) {
    / / the connection pool
    PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager();
    // Maximum number of connections
    poolingConnectionManager.setMaxTotal(1000);
    // Concurrency per host
    poolingConnectionManager.setDefaultMaxPerRoute(100);
    // Idle connection expiration time
    poolingConnectionManager.setValidateAfterInactivity(10 _000);
}
Copy the code

Create the HTTP factory class

@Bean
public HttpClientBuilder createFactory(a) {
    HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
    httpRequestFactory.setHttpClient(httpClientBuilder().build());
    // Connection request timeout
    httpRequestFactory.setConnectionRequestTimeout(3000);
    // The timeout period for establishing a connection between the client and the server
    httpRequestFactory.setConnectTimeout(3000);
    // The timeout period for reading data
    httpRequestFactory.setReadTimeout(120000);
    return httpRequestFactory
}
Copy the code

Finally, the HTTP factory class object is passed in when the RestTemplete object is created

RestTemplate restTemplate=new RestTemplate(httpRequestFactory);
Copy the code

2.2 Use the UTF-8 character set

RestTemplate StringHttpMessageConverter converter in the default to ISO – 8859-1 character set, the character set may cause garbled when convert Chinese characters, so you can modify the utf-8 character set.

// Get the set of converters in restTemplateList<HttpMessageConverter<? >> converterList = restTemplate.getMessageConverters();/ / traverse converter set, find the corresponding StringHttpMessageConverter converterHttpMessageConverter<? > converterTarget =null;
for(HttpMessageConverter<? > item : converterList) {if (StringHttpMessageConverter.class == item.getClass()) {
        converterTarget = item;
        break; }}// If there is a target converter, remove the existing converter
if (null! = converterTarget) { converterList.remove(converterTarget); }/ / add new StringHttpMessageConverter converter, and set the character set for utf-8
converterList.add(1.new StringHttpMessageConverter(StandardCharsets.UTF_8));
Copy the code

2.3 Using the FastJSON Converter

Spring’s json converter for RestTemplate is Jackson, which requires that the JSON string correspond strictly to the entity class to be converted. For ease of use, you can switch the JSON converter to Ali’s fastJson. Using Fastjson requires importing the dependency information first

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.54</version>
</dependency>
Copy the code

After that, you can remove the converter and add the FastJSON converter just as you did with the String message converter.

// Remove the original JSON converter
for(HttpMessageConverter<? > item : converterList) {if(converter instanceof GsonHttpMessageConverter || converter instanceofMappingJackson2HttpMessageConverter){ iterator.remove(); }}// Add fastjson converter
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
        SerializerFeature.WriteMapNullValue,
        SerializerFeature.WriteNullStringAsEmpty,
        SerializerFeature.WriteNullListAsEmpty,
        SerializerFeature.DisableCircularReferenceDetect);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
converterList.add(fastJsonHttpMessageConverter);
Copy the code

Finally, the restTemplate is returned to the Spring container for management, and the injected object is the custom restTemplate object when used.