Reprinted from: http://blog.sina.com.cn/s/blog_53786db50102e9m9.html
Overview: Nodejs claimed that the goal was "to provide a simple way to build a scalable network program", so what was the problem, what were its pros and cons, and what scenarios it was designed to address?
This article explores these issues in terms of personal experience.
I. Characteristics of NODEJS
Let's take a look at the introduction of the NODEJS official website:
node. JS is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. node. JS uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive R Eal-time applications that run across distributed devices.
Its features are:
1. It is a JavaScript runtime environment
2. Rely on the chrome V8 engine for code interpretation
3. Event-driven
4. Non-blocking I/O
5. Lightweight, scalable, suitable for real-time data interactive applications
6. Single process, single thread
Two. Solutions to system bottlenecks brought by Nodejs
Its appearance does provide us with new ideas and solutions to solve the system bottleneck in reality, let's see what it can solve.
1. Concurrent connections
For example, imagine a scenario where we queue up for business in a bank, and we look at the following two models.
(1) System Threading Model:
The problem with this model is obvious, the server has only one thread, the concurrent request (the user) arrives only one, the rest waits, this is the blocking, the request that is being enjoyed by the service blocks behind the request.
(2) Multithreading, thread pool model:
This model has progressed more than the previous one, it regulates the number of service threads to increase the reception and response to concurrent requests, but when the concurrency is high, the request still needs to wait, and it has a more serious problem. At the level of the code, let's look at the process of client-side requests for communication with the server:
The server and the client each establish a connection, to this connection to allocate a set of resources, mainly reflected in the system memory resources, in PHP, for example, to maintain a connection may require 20M of memory. This is why the general concurrency is large, you need to open the server more.
So how did Nodejs solve the problem? Let's look at another model and imagine the scene where we have a meal at a fast food restaurant.
(3) Asynchronous, event-driven model
We're also going to make a request to wait for the server to respond, but unlike the bank example, we get a number after the meal, get the number, we tend to wait in the position, and the request behind us continues to be processed, as well as taking a number and waiting for the receptionist to be able to handle it all the time.
Wait for the food to make the number, will shout the number, we got our own food, carries on the subsequent processing (eats). This call number action in the Nodejs called Callback (Callback), can be in the event (cooking, I/O) processing completed after the continuation of the logic (eat), which embodies the salient features of the NODEJS, the asynchronous mechanism, event-driven entire process does not block the connection of new users (ordering), There is no need to maintain a connection between the user who has ordered the meal and the chef.
Based on this mechanism, in theory, there are user requests to connect, Nodejs can respond, so nodejs can support higher concurrency than Java, PHP programs, although the maintenance event queue also cost, and because Nodejs is single-threaded, the longer the event queue, the longer the response time, Concurrency is still too much to go by.
summarize how Nodejs solves the problem of concurrent connections: Change the way you connect to the server, each connection launches (emit) an event that runs in the Nodejs engine process, and puts it into the event queue, Instead of generating a new OS thread for each connection (and allocating some companion memory for it).
2. I/O blocking
Another problem that Nodejs solves is I/O blocking, and look at the business scenario where you need to pull data from multiple data sources and then process it.
(1) Serial data acquisition, which is our general solution, take PHP as an example
If you need 1S for both profile and timeline operations, then serial acquisition requires 2S.
(2) Nodejs non-blocking I/O, transmit/listen events to control the execution process
Nodejs encountered I/O event will create a thread to execute, and then the main thread will continue to execute, therefore, take the action of profile to trigger an I/O event, will immediately execute the action of taking timeline, two actions parallel execution, if each need 1S, then the total time is 1S. After their I/O operations are completed, an event, profile, and timeline are emitted, and the event agent receives and continues to perform the subsequent logic, which is the feature of Nodejs non-blocking I/O.
To summarize: Java, PHP also has the means to implement parallel requests (sub-threads), but nodejs through the callback function (Callback) and asynchronous mechanism will do very naturally.
Three. Advantages and disadvantages of Nodejs
Advantages: 1. High concurrency (the most important advantage)
2. Suitable for I/O intensive applications
Disadvantages: 1. Not suitable for CPU-intensive applications; The main challenge for CPU-intensive applications is that because of the JavaScript single thread, if there are long-running computations (such as cycle), the CPU time slices will not be released, so that subsequent I/O cannot be initiated;
Solution: The decomposition of large operational tasks for a number of small tasks, so that the operation can be released in a timely manner, not blocking the initiation of I/O calls;
2. Only single-core CPUs are supported, and the CPU is not fully utilized
3. Low reliability, once the code one link crashes, the entire system crashes
Cause: Single process, single thread
Solution: (1) NNIGX reverse proxy, load balancing, open multiple processes, bind multiple ports;
(2) Open more than one process to listen to the same port, using the cluster module;
4. Open Source Component library quality is uneven, update fast, down incompatible
5. Debug is not convenient, error does not stack trace
Four. Suitable for nodejs scenes
1. RESTful API
This is Nodejs ideal application scenario, can handle tens of thousands of connections, itself does not have too much logic, only need to request the API, organize the data to return. It essentially simply looks up some values from a database and makes them a response. Because the response is small text, inbound requests are also small amounts of text, so traffic is not high, and a machine can even handle the API needs of the busiest companies.
2. Unifying the UI layer for Web Apps
The current MVC architecture, in a sense, Web development has two UI layers, one in the browser we finally see, the other on the server side, responsible for generating and splicing pages.
Not discussing whether this architecture is good or bad, but there is another practice, service-oriented architecture, better to do the front-end dependency separation. If all of the key business logic is encapsulated as a rest call, it means that you need to think about how to build a specific application with these rest interfaces on top. Those back-end programmers don't worry about how specific data is delivered from one page to another, and they don't have to worry about whether user data updates are asynchronously acquired through Ajax or by refreshing the page.
3. Application of a large number of Ajax requests
For example, the personalization application, each user sees the page is different, the cache is invalid, needs to initiate the AJAX request when the page loads, the NODEJS can respond the massive concurrent request. In summary, Nodejs is suitable for scenarios where high concurrency, I/o intensive, and small business logic are used.
Five. End
In fact, Nodejs can achieve almost all of the application, we consider the point is only appropriate to use it to do.
Advantages and disadvantages of Nodejs and discussion of applicable scenarios