Learning record remote call (HttpClient,RestTemplate, integrate custom connection pool, integrate SpringBoot test class)

Keywords: Programming Apache Spring JSON Lombok

Remote call

1. overview

  • One project wants to call the functionality of another

  • "User management system" calls "commodity management system",

    We call it "remote call". At this time, "user management system" is equivalent to simulating "browser".

2. Call mode

  • RPC: the remote call mode of custom data format, which is more inclined to the bottom layer
    • Common framework: dubbo
  • http: it adopts http remote call protocol and specifies the way of data transmission. The disadvantage is that the message package is too bulky
    • Now the popular Rest style can be realized through http protocol
    • Common framework: HttpClient,RestTemplate
Difference HTTP RPC
speed slower fast
difficulty simple complex
flexibility Flexible, cross platform, cross language

Getting started with 3HttpClient

  • Identify maven environment
   <!--Determine spring boot Version-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <dependencies>
        <!--web Start dependence-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <!--Support lombok-->
        <dependency>
            <groupId>lombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.0</version>
        </dependency>
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.49</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
  • Use HttpClient to send Get request
		CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
		try {
            //1 create Httpclient object (default connection), which is equivalent to opening browser
            CloseableHttpClient httpClient = HttpClients.createDefault();

            //2 determine the request mode and request path, which is equivalent to entering the address in the browser
            HttpGet httpGet = new HttpGet("http://localhost:9090/user");

            //3. Execute the request and get the response, which is equivalent to pressing enter after tapping the address.
            CloseableHttpResponse response = httpClient.execute(httpGet);

            //4 judge status code
            if(response.getStatusLine().getStatusCode() == 200){
                //5.1 types of response data obtained
                System.out.println(response.getEntity().getContentType());
                //5.2 get the response body content and use the entityutilities tool to process it
                String str = EntityUtils.toString(response.getEntity(),"UTF-8");
                System.out.println(str);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
          //6 release resources
          response.close();
          httpClient.close();
        }
  • Use HttpClient to send Post request

    		CloseableHttpClient httpClient = null;
            CloseableHttpResponse response = null;
            try {
                httpClient = HttpClients.createDefault();
    
                HttpPost httpPost = new HttpPost("http://localhost:9090/user");
                //  Set request header
                httpPost.setHeader("content-type","application/json;charset=utf-8");
                //  Set and process request body
                String str = "{\"username\":\"jack\",\"password\":\"1111\"}";
                httpPost.setEntity(new StringEntity(str,"utf-8"));
    
                response = httpClient.execute(httpPost);
    
                if (response.getStatusLine().getStatusCode() == 200){
                    System.out.println(EntityUtils.toString(response.getEntity()));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                response.close();
                httpClient.close();
            }
    
  • Use HttpClient to send Put request

    		CloseableHttpClient httpClient = null;
            CloseableHttpResponse response = null;
            try {
                httpClient = HttpClients.createDefault();
                HttpPut httpPut = new HttpPut("http://localhost:9090/user");
                httpPut.setHeader("content-type","application/json;charset=utf-8");
                String jsonStr = JSON.toJSONString(new User(1, "jack", "1111", 18));
                httpPut.setEntity(new StringEntity(jsonStr,"utf-8"));
    
                response = httpClient.execute(httpPut);
    
                if (response.getStatusLine().getStatusCode() == 200){
                    System.out.println(EntityUtils.toString(response.getEntity()));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                response.close();
                httpClient.close();
            }
    
  • Use HttpClient to send Delete request

    		CloseableHttpClient httpClient = null;
            CloseableHttpResponse response = null;
            try {
                //1. Create a client
                httpClient = HttpClients.createDefault();
                //2. Create a DELETE instance
                HttpDelete httpDelete = new HttpDelete("http://localhost:9090/user/1");
                //3. Send request
                response = httpClient.execute(httpDelete);
                //4. Judge the status code
                if (response.getStatusLine().getStatusCode() == 200){
                    //5. Utility processing response data
                    System.out.println(EntityUtils.toString(response.getEntity()));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //6. Release resources
                response.close();
                httpClient.close();
            }
    

4.RestTemplate

  • RestTemplate is the client provided by Spring to access the Rest service,

    RestTemplate provides a variety of convenient ways to access remote Http services, which can greatly improve the writing efficiency of clients

  • Get request

      [@Test](https://my.oschina.net/azibug)
        public void testGet(){
            RestTemplate restTemplate = new RestTemplate();
            //  Set url, return value type
            ResponseEntity<BaseResult> entity = restTemplate.getForEntity("http://localhost:9090/user", BaseResult.class);
            //  Return status code
            System.out.println(entity.getStatusCode());
            //  Return response body
            System.out.println(entity.getBody().getData());
        }
    
  • Post request

     [@Test](https://my.oschina.net/azibug)
        public void testLogin(){
            RestTemplate restTemplate = new RestTemplate();
            //  Set url, request body (automatic processing), return value type
            ResponseEntity<User> entity = restTemplate.postForEntity("http://localhost:9090/user/login", new User(1,"jack","1234",18), User.class);
            System.out.println(entity.getStatusCodeValue());
            System.out.println(entity.getBody());
        }
    
  • Put request

    [@Test](https://my.oschina.net/azibug)
        public void testPut(){
            RestTemplate restTemplate = new RestTemplate();
             //  Set url
            restTemplate.put("http://localhost:9090/user",new User(1,"jack","1234",18));
            System.out.println("Modified success");
        }
    
  • Delete request

     [@Test](https://my.oschina.net/azibug)
        public void testDelete(){
            RestTemplate restTemplate = new RestTemplate();
            //  Set url
            restTemplate.delete("http://localhost:9090/user/1");
            System.out.println(" Delete successful");
        }
    

5.SpringBoot integrates HttpClient and RestTemplate custom connection pool

package com.czxy.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by Che on 2019/12/3
 */
@Configuration
public class HttpClientConfig {

    //1. Custom connection to httpClient
    @Bean
    public CloseableHttpClient httpClient(PoolingHttpClientConnectionManager connectionManager,
                                          RequestConfig requestConfig){
        return HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
    }

    //2. Configure PoolingHttpClientConnectionManager
    @Bean
    public PoolingHttpClientConnectionManager connectionManager(){
        //1. Httpclient connection manager
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        //1.1. Maximum connections
        connectionManager.setMaxTotal(1000);
        //1.2. Set the number of concurrent accesses
        connectionManager.setDefaultMaxPerRoute(20);

        return connectionManager;
    }

    //3. Configure RequestConfig
    @Bean
    public RequestConfig requestConfig(){
        //1.3. Request configuration RequestConfig
        return RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(500)
                .setSocketTimeout(10 * 1000)
                .build();
    }

    //4. Create a factory
    @Bean
    public ClientHttpRequestFactory requestFactory(HttpClient httpClient){
        return new HttpComponentsClientHttpRequestFactory(httpClient);
    }

    //5. Configure restTemplate
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory){
        RestTemplate template = new RestTemplate(requestFactory);
        //Microsoft AppLocale
        List<HttpMessageConverter<?>> list = template.getMessageConverters();
        for (HttpMessageConverter<?> mc : list) {
            if (mc instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) mc).setDefaultCharset(Charset.forName("UTF-8"));
            }
        }
        return template;
    }
}

6. Integrate spring boot test class

  • You can register the Spring container in the test code
package com.czxy;

import com.alibaba.fastjson.JSON;
import com.czxy.domain.User;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * Created by Che on December 4, 2019
 */
@RunWith(SpringRunner.class)    //spring integration junit
@SpringBootTest(classes = HttpClientApplication.class)      //spring integration startup class
public class Test04 {
  	
    @Resource
    private CloseableHttpClient httpClient;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private PoolingHttpClientConnectionManager connectionManager;
    @Resource
    private RequestConfig requestConfig;

    @Test
    public void testDemo02(){
        System.out.println(httpClient);
        System.out.println(restTemplate);
        System.out.println(connectionManager);
        System.out.println(requestConfig);
    }
}

Posted by callmubashar on Fri, 06 Dec 2019 04:33:48 -0800