Placement of RestTemplate

Placement of RestTemplate

RestTemplate is a module used to access Rest services in the Spring framework. It can be called through simple methods to implement various http requests, including GET, POST, PUT, DELETE, etc. Before using the RestTemplate, some configuration is required.

Add Maven dependency

First, the following Maven dependencies need to be added to the project:

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

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

Among them, spring-boot-starter-web can help us configure all the components required by web applications, and spring-boot-starter-web-services provides some extensions that may be needed, such as JSON and XML conversion and WSDL generator.

Create a RestTemplate Bean

Next, we need to create a RestTemplate Bean in the Spring container, the code is as follows:

@Configuration
public class RestTemplateConfiguration {

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

This class uses the @Configuration annotation to declare that this is a configuration class. Through the @Bean annotation, a Bean named restTemplate is declared, which will be injected into the place where RestTemplate needs to be used.

Common methods of RestTemplate

The following are some commonly used methods of RestTemplate:

  • getForObject(url, responseType, uriVariables): Used to initiate a GET request and return a response object of the specified type. For example:
String result = restTemplate.getForObject("https://www.example.com/api/users/{id}", String.class, userId);
  • postForObject(url, request, responseType, uriVariables): used to initiate a POST request. For example:
User user = new User();
// TODO:填充user对象
User createdUser = restTemplate.postForObject("https://www.example.com/api/users", user, User.class);

Placement RestTemplate

RestTemplate also supports some advanced features such as connection pooling and HTTP authentication. Here are some relevant configuration options:

@Configuration
public class RestTemplateConfiguration {

    @Bean
    public RestTemplate restTemplate() {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(100);  // 设置最大连接数
        connectionManager.setDefaultMaxPerRoute(20);  // 设置每个路由的最大连接数

        // 配置HTTP客户端
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .disableContentCompression()  // 禁止压缩
                .setDefaultRequestConfig(requestConfig)
                .setDefaultCredentialsProvider(credentialsProvider);

        // 创建HTTP客户端工厂
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(clientBuilder.build());

        // 创建RestTemplate
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // 配置HttpMessageConverter
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        restTemplate.setMessageConverters(messageConverters);

        return restTemplate;
    }
}

This configuration class uses PoolingHttpClientConnectionManager for connection pool management, and uses HttpComponentsClientHttpRequestFactory as the request factory when creating RestTemplate. When configuring clientBuilder, HTTP response body compression is disabled, and configurations such as request timeout and request retry times are set using the setDefaultRequestConfig method, and authentication information is also provided for the HTTP client.

The above is the basic configuration of RestTemplate, which can be extended or modified according to the needs of the project.

Guess you like

Origin blog.csdn.net/weixin_43167662/article/details/130945443