A preliminary understanding of the Node. js mechanism and its principles.

Source: Internet
Author: User

A preliminary understanding of the Node. js mechanism and its principles.

I. Advantages and Disadvantages of node. js

Node. js is a single thread.

The advantage is that

1) Simple

2) high performance, avoiding frequent thread switching overhead

3) The resource usage is small. Because it is a single thread, the memory usage is still very low under heavy load.

3) thread security, no lock, unlock, or deadlock issues

Php


Node. js


The downside is that

How to solve high concurrency?

Node uses asynchronous IO and event-driven (callback function) to solve this problem.

Generally, the high-concurrency solution provides a multi-threaded model that provides a thread for each business logic and uses system thread switching to compensate for the time overhead of synchronous I/O calls. Like apache, a request is a thread.

Node. js uses a single-threaded model and uses asynchronous request methods for all I/O operations to avoid frequent context switching. an event queue is maintained during js execution. When the program is executed, an event loop waits for the next event to arrive. After each asynchronous I/O request is completed, it is pushed to the event queue for execution.

For example:

For a simple database access operation, the traditional method is implemented in this way.

 res = db.query('SELECT * from some_table'); res.output();
When the code is executed to the first line, the thread will be blocked, wait for the query to return the result, and continue processing. Because of database queries, disk reads and writes, network communication, and other reasons (so-called I/O), the blocking time will be very large (always frequency relative to the CPU ). For highly concurrent access, on the one hand, threads are blocked for a long time, and on the other hand, new threads are constantly added to cope with new requirements, which will waste a lot of system resources, at the same time, the increase of threads will also take a lot of CPU time to process memory context switching. How to deal with node. js

[Javascript]View plaincopy
  1. Db. query ('select * from some_table ', function (res ){
  2. Res. output ();
  3. });

The second parameter of query is a callback function. When the process runs to db. query, it does not wait for the result to be returned, but directly continues to execute the following statement until it enters the event loop. When the database returns the execution result, the event is sent to the event queue. The callback function is called only after the thread enters the event loop.

Node. js's asynchronous mechanism is based on events. All I/O, network communication, and database queries are executed in a non-blocking manner, and the returned results are processed by the event loop. Node. js processes only one event at a time, and then immediately enters the event loop check. In this way, the CPU and the memory can process one thing at a time, and try to run time-consuming I/O operations in parallel.


Event Loop Mechanism

The so-called event loop means that node. js uses the event mechanism to solve all asynchronous operations, and a thread continuously cyclically detects event queues.

All logics of node. js are Event Callback functions. Therefore, node. js is always in the event loop, and the program entry is the callback function of the first event in the event loop. The callback function of the event may send an I/O Request or directly launch an (emit) event. After the execution is completed, the event loop is returned. The event loop checks whether there are any unprocessed events in the event queue until the program ends. Node. the js event loop is invisible to developers and implemented by the libev library. libev constantly checks whether there are active event listeners that can be detected. It does not exit the event loop until the check fails, the program ends.


Libuv is a high-performance event-driven library that encapsulates some underlying features of Windows and Unix platforms and provides developers with a unified API.
Therefore, node. js is a single thread and asynchronous and non-blocking.

But after all, how can we make up for single-thread defects? Is there an asynchronous non-blocking mechanism, so you can rest assured?

No.

1) CPU-intensive tasks are short-lived.

As mentioned above, the nodejs mechanism is a single thread, which contains an event Loop Mechanism to process all requests .. In the event processing process, it intelligently submits some time-consuming operations related to IO and network communication to worker threads for execution, and calls back after the execution is complete, this is the so-called asynchronous IO non-blocking. However, for non-I/O operations, they only use CPU computing operations, such as the Fibonacci series. It is a single thread. These self-carried tasks need to be completed one by one. The previous tasks are not completed, and the subsequent tasks can only be done. Therefore, if there are many CPU-intensive tasks with high CPU requirements, it may result in high performance, suitable for high-concurrency node. js servers to respond slowly.



2) CPU multi-core cannot be used

At the beginning, the thread is only used to allocate a single processor's processing time. However, if the operating system itself supports multiple CPUs/kernels, each thread can obtain a different CPU/kernel to implement real "parallel operations ". In this case, multi-threaded programs can improve resource usage efficiency. Node. js is a single-threaded program. It only has one event loop and only occupies one CPU/kernel. Currently, most servers use multiple CPUs or cores. the event loop of js programs is occupied by CPU-intensive tasks. When other tasks are blocked, the CPU/kernel is idle, resulting in a waste of resources.


Solution

Use native or third-party modules to open up processes or sub-processes for processing these special tasks.

3) if an exception is thrown, because it is a single thread, the entire project will be unavailable. But this is ultimately a code problem. Bad code, no matter what system, will have problems, even if it does not crash. The solution is to use pm2 and other tools for running?

Ii. Relationship between nodejs and javascript

Nodejs is not a development language. It is a tool or platform that explains and runs javascript on the server. coffeescript is a nodejs system and is a new development language, but its purpose is to compile it into javascript.

Nodejs uses Google V8 to explain how to run javascript, but the Code actually executed by the system is written in C ++. Javascript only calls these Apis. Therefore, there is no execution efficiency problem.



Iii. Applicable scenarios of nodejs


1. RESTful API

This is ideal for Node because you can build it to process tens of thousands of connections. It still does not require a lot of logic; in essence, it simply finds some values in a database and forms a response. Because the response is a small amount of text, the inbound request is also a small amount of text, so the traffic is not high, a machine can even handle the API requirements of the busiest companies.

2. Real-time programs

For example, chat service

Chat applications are examples that best reflect the advantages of Node. js: lightweight, high-traffic, and good response to running-intensive data on cross-platform devices (although low computing power ). At the same time, chatting is also a case worth learning, because it is very simple and covers most of the solutions used by a typical Node. js so far.

3. Single-page APP

A lot of ajax. Currently, the single-page mechanism seems to be quite popular. For example, the APP developed by phonegap, there are many examples of page packaging.


...


All in all, NodeJS is applicable to scenarios with high concurrency, I/O intensive, and a small amount of business logic.



References

Misunderstanding about node. js

Node. js threads and processes

Http://www.slideshare.net/mysqlops/nodejs-9313477

Node. js vulnerabilities-CPU-intensive tasks

Http://www.ruanyifeng.com/blog/2014/10/event-loop.html

Http://segmentfault.com/a/1190000000375619

Http://www.cnblogs.com/sysuys/p/3460614.html


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.