In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "how to use RestTemplate". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
I. Overview
This paper mainly introduces the principle, advantages and disadvantages of RestTemplate components in Spring Web module, and how to expand to meet various requirements.
Before introducing RestTemplate, let's talk about HTTP Client, the importance of choosing a good HTTP Client implementation, and what features a good HTTP Client should have.
In the Java community, HTTP Client mainly includes JDK's HttpURLConnection, Apache Commons HttpClient (or Apache HttpClient 3.x), Apache HttpComponents Client (or Apache HttpClient 4.x), and Square's open source OkHttp.
In addition to these pure HTTP Client class libraries, there are Spring's RestTemplate, Square's Retrofit, Netflix's Feign, and client components like Apache CXF. These frameworks and class libraries are primarily targeted at Web Service scenarios, especially RESTful Web Service. They are often based on the HTTP Client implementation mentioned earlier, and provide message transformation, parameter mapping and other functions that are necessary for Web Service.
(of course, for network IO frameworks such as Netty and Mina, it is no longer necessary to implement HTTP, but these frameworks are usually too low-level to be used directly.)
The importance of choosing a good HTTP Client
Although calls between services are increasingly using RPC and message queues, HTTP still has scenarios that suit it.
The advantages of RPC lie in an efficient network transport model (often implemented using NIO), as well as specially designed protocols and efficient serialization techniques for service invocation scenarios. The advantage of HTTP lies in its mature and stable, easy to use and implement, widely supported, good compatibility, firewall-friendly and high readability of messages. Therefore, it is widely used in scenarios where open API, cross-platform inter-service invocation, and no stringent performance requirements.
Officially, because HTTP has a wide range of application scenarios, it is very important to choose an excellent HTTP Client.
The characteristics that excellent HTTP Client needs to have
Connection pool
Timeout settings (connection timeout, read timeout, etc.)
Whether async is supported
Codec of request and response
Expandability
Connection pool
Because HTTP 1.1 currently does not support multiplexing, only HTTP Pipeline is supported by the semi-multiplexing model. Therefore, in scenarios where messages need to be sent frequently, connection pooling must be supported to reduce unnecessary performance loss caused by frequent connection establishment.
Timeout settings (connection timeout, read timeout, etc.)
When there is a problem with the peer, a long or even unlimited timeout wait is absolutely unacceptable. So you must be able to set the timeout.
Whether async is supported
HTTP-related technologies (server-side and client-side) are generally considered to be an important reason for poor performance because HTTP-related implementations lack support for asynchrony for a long time. This refers not only to non-blocking IO, but also to the asynchronous programming model. The consequence of the lack of an asynchronous programming model is that even if the HTTP stack is implemented based on non-blocking IO, threads that call the client or process messages on the server side waste a lot of time waiting for IO. Therefore, asynchrony is a very important feature.
Codec of request and response
In general, developers want to use a variety of services for object orientation (which naturally includes services based on the HTTP protocol), rather than directly facing the original message and response development. Therefore, it is necessary to transparently encode and decode HTTP requests and responses, as this can greatly reduce the workload of developers.
Expandability
No matter how well a framework is designed, there are always special scenarios that they cannot support natively. At this point, the quality of scalability is reflected.
Answer
Based on the above considerations, RestTemplate is a relatively good choice. The reason is that RestTemplate itself is based on mature HTTP Client implementations (Apache HttpClient, OkHttp, etc.), and can be flexibly switched between these implementations, and has good scalability. The most important thing is to provide the message codec capabilities that the previous HTTP Client does not have.
Here is a reason why you didn't encapsulate HTTP Client yourself. The reason for this is that it is not difficult to provide message codec capabilities and certain scalability based on a HTTP Client, but it is not easy to design a general framework that is transparent to the underlying implementation and has excellent extensibility such as Spring. The difficulty here is not how advanced the technology is, but that good extensibility design often comes from a wealth of first-line practical experience from many good programmers, communities and software companies, and then transformed from things like Spring to the final design. Such a product cannot be obtained overnight. Before we think we can build our own tools, we can get an in-depth understanding of what the existing excellent features can do.
Second, the disadvantages of using RestTemplate
If you want to promote and suppress first, let's first take a look at what "pits" you may encounter when you join the use of RestTemplate.
Rely on other modules of Spring
Although the spring-web module does not explicitly depend on other Spring modules (Maven dependency's scope is compile), for some features, such as the asynchronous version of RestTemplate, a version of spring-core module above 4.1 is required.
Therefore, for RestTemplate to give full play to its function, it is best to have other Spring modules of similar versions (spring-core, spring-context, spring-beans, spring-aop).
Shortcomings of RestTemplate by default
RestTemplate in the Spring Web module is a good client for RESTful Web services. It provides many features to simplify the invocation of RESTful Web services, such as Path Parameter formatting (/ hotels/ {hotel_id} / books/ {book_id}, where hotel_id and book_id are Path Paramter), transparent conversion between data in JSON or XML format and entity classes, and so on.
The default means not to extend the classes or interfaces provided by RestTemplate, but to rely entirely on the code provided by itself. In this case, RestTemplate still has some inconveniences. For example, its Path Parameter formatting capability becomes a disadvantage for normal HTTP service calls, because ordinary HTTP service GET methods often use Query Parameter instead of Path Parameter. The form of Query Paramter is an_http_url?name1=value1&name2=value2. For example, getOrder.action?order_code=xxx. If you use RestTemplate, the URL passed to RestTemplate as an argument must be getOrder.action?order_code= {order_code}. If the parameters are fixed, it would be inconvenient if the Query Parameter of a HTTP service is variable.
Third, expand RestTemplate
Note that the code involved below is based on the spring-web 4.2.6.RELEASE version
Set up Query Params
As mentioned above, the Map parameter in RestTemplate's getForEntity, getForObject, postForEntity, and other methods is uriVariables, which we often call PathParam, rather than QueryParam (the definitions of these two parameters can be found in @ PathParam and @ QueryParam in JAX-RS).
Path Param is a part of URL, and the Web Service of RESTful parses its corresponding value from URL according to its defined URL Template.
This mechanism of RestTemplate is undoubtedly convenient for RESTful's Web Service, but in many cases we still want RestTemplate to send parameters of type Map as Query Param to peer services without having to write extra code.
Fortunately, RestTemplate from the Spring family is also extensible, with an extension point called UriTemplateHandler. Because both Path Param and Query Param are part of URI, you only need to implement a custom URI generation mechanism to solve this problem.
By extending DefaultUriTemplateHandler, we can also use Map uriVariables as a Query Param. The specific implementation is as follows:
Public class QueryParamsUrlTemplateHandler extends DefaultUriTemplateHandler {@ Override public URI expand (String uriTemplate, Map uriVariables) {UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl (uriTemplate); for (Map.Entry varEntry: uriVariables.entrySet ()) {uriComponentsBuilder.queryParam (varEntry.getKey (), varEntry.getValue ());} uriTemplate = uriComponentsBuilder.build (). ToUriString (); return super.expand (uriTemplate, uriVariables);}}
The above implementation is based on DefaultUriTemplateHandler, so it retains the function of setting up Path Param.
Set custom HTTP Header
There are several ways to achieve this requirement, such as through interceptors. Another method is used here, through a custom ClientHttpRequestFactory
Public class CustomHeadersClientHttpRequestFactoryWrapper extends AbstractClientHttpRequestFactoryWrapper {private HttpHeaders customHeaders = new HttpHeaders (); / * * Create a {@ code AbstractClientHttpRequestFactoryWrapper} wrapping the given request factory. * * @ param requestFactory the request factory to be wrapped * / protected CustomHeadersClientHttpRequestFactoryWrapper (ClientHttpRequestFactory requestFactory) {super (requestFactory);} @ Override protected ClientHttpRequest createRequest (URI uri, HttpMethod httpMethod, ClientHttpRequestFactory requestFactory) throws IOException {ClientHttpRequest request = requestFactory.createRequest (uri, httpMethod); for (Map.Entry headerEntry: customHeaders.entrySet ()) {request.getHeaders (). Put (headerEntry.getKey (), headerEntry.getValue ()) } return request;} public void addHeader (String header, String...) Values) {customHeaders.put (header, Arrays.asList (values));}} simplify configuration
RestTemplate provides good scalability, but some settings use ``
IV. RestTemplate principle parsing HTTP Client implementation
RestTemplate itself does not do the underlying implementation of HTTP, but makes use of existing technologies, such as JDK or Apache HttpClient.
RestTemplate needs to provide a ClientHttpRequest implementation for it using a class that implements the ClientHttpRequestFactory interface (and AsyncClientHttpRequestFactory corresponds to an asynchronous HTTP implementation, which is not shown here). The ClientHttpRequest implementation encapsulates the underlying details of assembling, sending HTTP messages, and parsing responses.
At present, there are four main implementations of ClientHttpRequestFactory in (4.2.6.RELEASE) RestTemplate, which are:
SimpleClientHttpRequestFactory based on JDK HttpURLConnection
HttpComponentsClientHttpRequestFactory based on Apache HttpComponentsClient
OkHttpClientHttpRequestFactory based on OkHttp 2 (the latest version of OkHttp is 3, with major changes, package name changes, and is not compatible with the previous version)
Netty4ClientHttpRequestFactory based on Netty4
In addition, there is an InterceptingClientHttpRequestFactory that provides interceptor functionality.
Write a message
Writing a message refers to the process of transforming requestBody into data in a certain format, such as JSON or XML.
The spring-web module provides a HttpMessageConverter interface for reading and writing HTTP messages. This interface is used not only by RestTemplate but also by Spring MVC.
The spring-web module provides HttpMessageConverter based on Jackson, GSON and other class libraries, which is used to convert data in JSON or XML format.
When sending a message, RestTemplate determines which HttpMessageConverter to use to write the message based on the ContentType of the message or some properties of the RequestBody object itself.
Specifically, if RequestBody is a HttpEntity, the ContentType attribute is read from it. At the same time, the RequestBody object itself will feel whether a HttpMessageConverter will handle the object. For example, ProtobufHttpMessageConverter requires that the RequestBody object must implement the com.google.protobuf.Message interface.
Read the message
A read message refers to reading the data in HTTP Response and converting it to a user-specified format (specified by the Class responseType parameter). Similar to the processing of writing messages, the processing of reading messages is also carried out through the corresponding HttpMessageConverter selected by ContentType and responseType.
Error handling
RestTemplate provides an interface to ResponseErrorHandler to handle incorrect Response. You can implement the extension by setting a custom ResponseErrorHandler.
Postscript
According to the ideas I have expressed above, a tool has been created to unify, standardize, and simplify the use of RestTemplate, but for the time being, the code is not available because it is part of the company's project. And I hope it will be better to contribute this tool after more practical tests.
A complete current use case is as follows:
@ Configurationpublic class SpringConfigurationDemo {@ Bean public RestTemplate myRestTemplate () {return RestTemplateBuilder.create () .withClientKey ("myRestTemplate") .implementation (HttpClientImplementation.OK_HTTP) .clearMessageConverters () .setMessageConverter (new MappingJackson2HttpMessageConverter () MediaType.TEXT_PLAIN) .enableAutoQueryParams () .connectTimeout (100) .readTimeout (200) .header (HttpHeaders.USER_AGENT, "MyAgent") .build () }}
Although RestTemplate is a good HTTP Client, Netflix has opened up a better HTTP Client tool-Feign. It is a declarative HTTP Client that is significantly ahead of existing tools in terms of ease of use, readability, and so on. I plan to write an article later to analyze the ideas, principles and advantages of Feign (the principle is not complicated, but few can think of doing so, original innovative ideas are always the most valuable)
This is the end of "how to use RestTemplate". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.