Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the correct use of RestTemplate under the practical high concurrency of java

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what is the correct use of RestTemplate under the practical high concurrency of java". In daily operation, I believe that many people have doubts about the correct use of RestTemplate under the practical high concurrency of java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "what is the correct use of RestTemplate under the practical high concurrency of java?" Next, please follow the editor to study!

Preface

If there is a http interface that calls a third party in the java project, we can use RestTemplate to access it remotely. You can also configure connection timeout and response timeout, configure various persistent connection strategies, and support long connection preheating. Under high concurrency, reasonable configuration can effectively improve the response time of third-party interfaces.

What is RestTemplate?

RestTemplate is a client provided by Spring to access Rest services. RestTemplate provides a variety of convenient methods to access remote Http services, which can greatly improve the writing efficiency of the client.

Second, how to use 1. Create a bean

The following code is relatively simple to configure, setting only the connection timeout and response timeout

/ * * restTemplate configuration * * @ author Songsong * @ date 2020-08-17 15:09 * / @ Configurationpublic class RestTemplateConfiguration {@ Bean (name = "restTemplate") public RestTemplate restTemplate () {SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory (); / / set connection timeout 1s factory.setConnectTimeout (1000); / / set read time 1s factory.setReadTimeout (1000); return new RestTemplate (factory);}} 2. Use steps

Use @ Resource or @ Autowired injection where needed

@ Resourceprivate RestTemplate restTemplate

Then the APIs we usually call third parties are get and post. RestTemplate provides getForEntity and postForEntity methods to support these two methods. You can call them directly. The source codes are as follows:

GetForEntity method:

Public ResponseEntity getForEntity (String url, Class responseType, Object... UriVariables) throws RestClientException {RequestCallback requestCallback = this.acceptHeaderRequestCallback (responseType); ResponseExtractor responseExtractor = this.responseEntityExtractor (responseType); return (ResponseEntity) nonNull (this.execute (url, HttpMethod.GET, requestCallback, responseExtractor, uriVariables);}

PostForEntity method:

Public ResponseEntity postForEntity (String url, @ Nullable Object request, Class responseType, Object...) UriVariables) throws RestClientException {RequestCallback requestCallback = this.httpEntityCallback (request, responseType); ResponseExtractor responseExtractor = this.responseEntityExtractor (responseType); return (ResponseEntity) nonNull (this.execute (url, HttpMethod.POST, requestCallback, responseExtractor, uriVariables);}

There are many of the above two other overloading methods in the source code. These are the most commonly used in the author's daily projects. The parameters include url (third-party http link), request is the required parameter for the request, and responseType is the generics in the return type.

You only need to parse the returned parameters.

Third, the use of RestTemplate under high concurrency

In ordinary development, the above simple configuration may be enough, but in high concurrency, the interface response time is very high, so we need to improve the third-party interface response time as much as possible. HttpClient persistent connection can be used in RestTemplate. We can refer to the introduction of httpClient persistent connection: HTTPclient keep persistent connection.

In the following code, we set up the function of long connection preheating and the number of routing concurrency:

@ Slf4j@Configurationpublic class RestTemplateConfiguration {@ Bean (name = "restTemplate") public RestTemplate restTemplate () {return getRestTemplate (3, "https://www.baidu.com/......");} private RestTemplate getRestTemplate (int maxTotal, String preHeatUrl) {HttpComponentsClientHttpRequestFactory httpRequestFactory = httpComponentsClientHttpRequestFactory (maxTotal); RestTemplate restTemplate = new RestTemplate (httpRequestFactory)) / / resolve the first prefetch time if (StringUtils.isNotEmpty (preHeatUrl)) {try {restTemplate.postForEntity (preHeatUrl, ", String.class);} catch (Exception e) {log.error (" preHeat url error: {} ", e.getMessage ());}} return restTemplate } / * another implementation of ClientHttpRequestFactory interface (recommended): * HttpComponentsClientHttpRequestFactory: the underlying layer uses Httpclient connection pool to create Http connection requests * * @ return * / private HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory (int maxTotal) {/ / Httpclient connection pool, long connection retention time PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager (1, TimeUnit.HOURS) / / set the total number of connections connectionManager.setMaxTotal (maxTotal); / / set the number of concurrency with the route connectionManager.setDefaultMaxPerRoute (maxTotal); / / set header List headers = new ArrayList (); headers.add (new BasicHeader ("User-Agent", "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.04") Headers.add (new BasicHeader ("Accept-Encoding", "gzip, deflate"); headers.add (new BasicHeader ("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")); headers.add (new BasicHeader ("Connection", "keep-alive")) / / create HttpClient HttpClient httpClient = HttpClientBuilder.create () .setConnectionManager (connectionManager) .setDefaultHeaders (headers) .setRetryHandler (new DefaultHttpRequestRetryHandler (3, true)) / / set the number of retries. SetKeepAliveStrategy (new DefaultConnectionKeepAliveStrategy ()) / set persistent connection .build () / / create HttpComponentsClientHttpRequestFactory instance HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory (httpClient); / / set the timeout requestFactory.setConnectTimeout for establishing a connection between the client and the server (10000); / / set the timeout requestFactory.setReadTimeout for the client to read data from the server (5000) / / set the timeout for obtaining connections from the connection pool, which should not be too long requestFactory.setConnectionRequestTimeout (2000); / / buffer request data. Default is true. When sending large amounts of data through POST or PUT, it is recommended to change this to false to avoid running out of memory requestFactory.setBufferRequestBody (false); return requestFactory;} 1. Set up warm-up function

As we can see, in the getRestTemplate method

Return restTemplate

It was requested once before, that is, when you need to use the service layer injection called by third-party APIs, it is called in advance. According to the characteristics of persistent connections, the first connection usually takes a long time. After using it, the connection will not be recycled immediately, and it will still survive for a certain period of time. Therefore, under high concurrency, the response time of the interface after preheating will be greatly improved.

two。 Set the number of maxtotal reasonably

We can see the following code

/ / set the total number of connections connectionManager.setMaxTotal (maxTotal)

We can see that in this line, maxTotal sets the total number of connections. This setting needs to be set according to the response time of the interface and the QPS that needs to be supported. For example, the response time of the interface is 100ms, and the QPS that needs to be supported is 5000, that is, 5000 pounds. Then a long connection for 1 second is able to handle 10 requests. Then the total number of maxTotal is 500. this is the approximate number set, but sometimes QPS is not so stable. So the specific setting depends on the specific situation.

For more information on RestTemplate depth analysis, please see RestTemplate depth Analysis.

At this point, the study on "what is the correct use of RestTemplate under the practical high concurrency of java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report