In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
In this issue, the editor will bring you about the basic usage of responsive non-blocking IO. The article is rich in content and analyzes and describes it from a professional point of view. I hope you can get something after reading this article.
RestTemplate, as part of the spring-web project, was introduced in Spring version 3.0. According to the official Spring documentation and source code, RestTemplate may be deprecated in future releases. Instead, Spring has officially introduced WebClient as a non-blocking Reactive HTTP client in Spring 5.
What is responsive non-blocking IO
Before we begin to introduce webClient, it is necessary to introduce the differences between responsive non-blocking IO and traditional IO. Let's start with the question: is it faster for webClient to send and receive a single HTTP request than RestTemplate? The answer is no. Seeing that some students here have been confused, since webClient is not faster, why do the authorities recommend it? Listen to me go on.
1.1. Traditional blocking IO model
The author uses relatively popular words to explain the difference between blocking IO and non-blocking IO. Let's make an analogy to the way the software development team works. As software developers, we certainly know the basic process of software development:
Project establishment and feasibility study
Requirement analysis and design
Code development
Iterative testing
Launch and configuration management, operation and maintenance
The framework represented by Spring MVC or struct is based on sevlet, and the underlying IO model is the blocking IO model. This model is as if you are a developer in the company, and all five tasks above are done by you alone. If there are 10 people in the company, you can only have 10 requirements at the same time. There is nothing we can do about the increase in customer demand, but to keep them waiting. As shown in the following figure: a request occupies one thread, and when all the threads in the thread pool are occupied, the new request can only wait.
1.2. Responsive IO model
In order to solve the performance bottleneck of Spring MVC blocking model in high concurrency scenarios, the spring community has proposed a tried-and-tested Spring WebFlux,WebFlux non-blocking IO communication framework. The interaction diagram between request processing and threads of the framework is as follows:
BoosGroup is used for Accetpt connection establishment events and dispatch requests, and workerGroup is used to handle I _ write events. I won't elaborate on netty, but I'll tell you about it in a popular way: if you compare the combination of task pools and thread pools in the above figure to a software development company, then:
Project establishment and feasibility research shall be completed by the company's project manager and consultant.
Requirements analysis and design, completed by product managers and architects
Code development, which is completed by the project manager and the developers.
Iterative testing, completed by the test team
Launch, configuration management, operation and maintenance may be completed by a special devops team
In this way, when all the people in a company complete the division of labor, they will be able to contact more customers, talk about more needs, allocate human resources reasonably and reach the limit level of maximizing concurrent processing capacity under the condition of limited resources. Compared with an employee in charge of a project from scratch, it is more organized, more clear division of labor, rational use of free resources, the most professional thing for professional people.
There are similarities and differences between the rational utilization and organization of human resources and the non-blocking IO model. Through reasonable classification of request processing threads and tasks, reasonable use of system memory and CPU resources to maximize processing capacity per unit time is the core intention of asynchronous non-blocking IO! Going back to the problem left above, webClient doesn't respond to a single HTTP request any faster than RestTemplate, but it has a better ability to handle concurrency. Therefore, the core significance of the responsive non-blocking IO model is to improve the concurrent processing ability of service requests under limited resources per unit time, rather than shorten the response time of a single service request.
Second, the advantages of WebClient
After introducing the IO model above, I think you can understand it. Compared with RestTemplate, WebClient has the following advantages:
Non-blocking responsive IO that supports higher concurrency with limited resources per unit time
Support for using Java 8 lambda expression functions
Simultaneous support for synchronous, asynchronous and Streaming streaming scenarios
III. Introducing WebClient into the project
To use WebClient, you need to introduce the following Jar (which can be introduced in Spring Boot projects that contain spring-boot-starter-web)
Org.springframework.boot spring-boot-starter-webflux
Then the problem comes again, and friends who are familiar with Spring development should know it. Spring-boot-starter-webflux and spring-boot-starter-web represent two sets of technology stacks
Spring-boot-starter-web can realize the relatively mature Spring Boot application based on servlet technology stack.
What spring-boot-starter-webflux can realize is the Spring Boot application of the underlying netty-based responsive programming technology stack.
Can the two coexist? The answer is:
As a server to implement Spring Boot applications, the two certainly can not co-exist from the application point of view. By the time I was writing in 20200820, if both were introduced into a project, the server application was actually developed using spring-boot-starter-web 's servlet-based technology stack.
As a HTTP client, if we just want to use WebClient. In any case, it is right to introduce spring-boot-starter-webflux.
IV. WebClient instance creation and basic usage
There are three ways to create WebClient. Let's introduce them one by one.
WebClient.create ()
WebClient.create (String baseUrl): baseUrl is specified, using this client to send requests is based on baseUrl
WebClient.builder () returns a WebClient.Builder that can be chained, passing more parameters.
In order to facilitate the follow-up development and testing, first introduce a website to you. JSONPlaceholder is a website that provides free online REST API, and we can use the url address it provides to test network requests and request parameters. Or when our program needs to get some simulation data, simulation pictures can also use it.
4.1. WebClient.create ()
Create a WebClient to send a GET request and receive a single Mono object of type String (mono, mono).
Public class SimpleTest {[@ Test] (https://my.oschina.net/azibug) void testSimple () {WebClient webClient = WebClient.create () Mono mono = webClient .get () / send GET request .uri ("http://jsonplaceholder.typicode.com/posts/1") / / request path .response () / / get the response result .bodyToMono (String.class); / / response data type conversion System.out.println (" = "+ mono.block ());}}
The mono.block () method is still a blocking data response receiving method, and the responsive programming method will be introduced in a later article.
4.2.WebClient.create (String baseUrl)
The create () no-parameter method is used above to specify the complete HTTP service path every time you specify a uri request, such as "http://jsonplaceholder.typicode.com/posts/1"." Using WebClient.create (String baseUrl), you can specify a baseUrl uniformly, so that when a request specifies a request uri, the baseUrl part, such as "/ posts/1", can be omitted.
Private WebClient webClient = WebClient.create ("http://jsonplaceholder.typicode.com");[@Test](https://my.oschina.net/azibug)void testBaseUrl () {Mono mono = webClient .get () .uri (" / posts/1 ") / / request path, note that the baseurl section .upload () .bodyToMono (String.class); System.out.println (" = "+ mono.block ());}
The above code requests the result, which is the same as the 4.1 result.
4.3.WebClient.builder ()
Using builder () to create a WebClient object enriches the content of the parameters that can be passed at once. Cookies, headers and other information can be transmitted using builder. Scenario: for example, the server you request uses JWT token, and each request needs to pass token. It would be troublesome to create a separate WebClient for each request and then specify a Token. We can use builder to set the Token uniformly when WebClient is instantiated.
Private WebClient webClient = WebClient .builder () .defaultHeader ("JWT-Token", "xxxyyy3fsfsfsff-fjdskfa") .build ()
The optional configurations supported are as follows:
UriBuilderFactory: custom UriBuilderFactory flexible configuration using Url
DefaultHeader: sets Headers request headers for HTTP requests
DefaultCookie: set Cookies for HTTP requests
DefaultRequest: custom Http Request
Filter: add a client filter to HTTP requests
ExchangeStrategies: HTTP read and write information customization
ClientConnector: HTTP client connector settin
This is the basic usage of responsive non-blocking IO shared by the editor. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
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.