javascript - Concurrent access to Node is inconsistent with the expected result
怪我咯
怪我咯 2017-06-22 11:54:23
0
1
789
  • The logic of the test is relatively simple, that is, Node accesses the database to query data. The execution time of the SQL statement is about 2 seconds. I used JMeter to conduct multi-thread testing (5 threads), and the results were as expected (according to Node non-blocking Features), 5 threads should return results in 2 seconds at the same time, but the result is like this:

  • According to the results, Node is executed serially, which is inconsistent with the expected result. Can anyone explain it

  • Code:

app.get('/', function (req, res) {
    var now = +(new Date())
    connection.query('select count(*) from ACTIVITY group by name', function (err, result, fields) {
        var curr = +(new Date())
        var tmp = '耗时:' + (curr - now)
        console.log(tmp)
        res.send(tmp)
    })
})
  • Note: It is not a database processing problem, because I use two different machines to execute the same SQL statement, and the time is 2 seconds


The following is a supplement

  • According to @Biancheng, the reason is that multiple SQL statements use the same connection. Now the code has been modified and the database connection pool is used. The execution result is as follows:

  • code show as below:

app.get('/', function (req, res) {
    var now = +(new Date())
    pool.getConnection(function (err, conn) {
        console.log('--连接池连接成功!' + +(new Date()))
        conn.query('select count(*) from ACTIVITY group by name', function (err, result, fields) {
            var curr = +(new Date())
            var tmp = '耗时:' + (curr - now)
            console.log(tmp)
            res.send(tmp)
        })
    })
})
  • This result is more consistent with expectations. Five threads query at the same time, and all returns are returned in 4 seconds. As the pressure increases, the query time will naturally become longer. After testing, when the number of threads is changed to 2 , the return time is 2s, which is consistent with expectations!

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
某草草

The start of time is before query and the end is when query is completed, so each time is the time when query is running,

Node is asynchronous, but you are using the same connection. Does the connection itself need to be queued? As far as I know, the SQL executed by most databases in the same connection is queued and executed one after another... Multiple connections may be parallel.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template