Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

为什么node.js有个查询慢的连接会拖慢查询快的连接?

$
0
0

index.js

var http = require('http');
var url = require('url');
var fs = require('fs');
var DBHelper = require('./dbHelper');
http.createServer(function (request, response) {
  var pathname = url.parse(request.url).pathname;
  if (pathname == '/') {
    fs.readFile(__dirname + '/index.html', function (err, data) {
      if (err) {
        console.log(err);
        // HTTP 状态码: 404 : NOT FOUND
        // Content Type: text/plain
        response.writeHead(404, { 'Content-Type': 'text/html' });
      } else {
        // HTTP 状态码: 200 : OK
        // Content Type: text/plain
        response.writeHead(200, { 'Content-Type': 'text/html' });

        // 响应文件内容
        response.write(data.toString());
      }
      //  发送响应数据
      response.end();
    });
  }
  else if (pathname == '/jquery-3.1.0.js') {
    fs.readFile(__dirname + '/jquery-3.1.0.js', function (err, data) {
      if (err) {
        console.log(err);
        // HTTP 状态码: 404 : NOT FOUND
        // Content Type: text/plain
        response.writeHead(404, { 'Content-Type': 'text/html' });
      } else {
        // HTTP 状态码: 200 : OK
        // Content Type: text/plain
        response.writeHead(200, { 'Content-Type': 'application/javascript' });

        // 响应文件内容
        response.write(data.toString());
      }
      //  发送响应数据
      response.end();
    });
  }
  else if(pathname=='/oo') {
    try {
      var dbHelper = new DBHelper();  
      
      (async () => {
        console.time(pathname+'_2')   
        let data = await dbHelper.query(`declare @i int 
        set @i=1 
        while @i<10000
        begin
        select top 2 * from tUser  with(nolock)
        set @i=@i+1
        end`,pathname);        //这里模拟查询慢的连接
        response.writeHead(200, { 'Content-Type': 'application/json' });
        response.end(JSON.stringify(data));
        console.timeEnd(pathname+'_2')
      })()
      
    }
    catch (e) {
      console.error(e)
    }

  }
  else  {
    try {
      var dbHelper = new DBHelper();   
     
      (async () => {
         console.time(pathname+'_1')  
        let data = await dbHelper.query('select top 2 * from tDept with(nolock)',pathname);        
        response.writeHead(200, { 'Content-Type': 'application/json' });
        response.end(JSON.stringify(data));
        console.timeEnd(pathname+'_1') 
      })()
      
    }
    catch (e) {
      console.error(e)
    }

  }

}).listen(8888);

dbHelper.js

const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
const config = {
    userName: 'sa', // update me
    password: '', // update me
    server: '',
    options: {
        port: '5555',
        database: '',
        rowCollectionOnRequestCompletion: true
    }
}

class DBHelper {
    constructor() {
        this.connection = new Connection(config);

    }
    async query(cmd,url) {
        var p = this;
        var promise = new Promise((resolve, reject) => {
            p.connection.on('connect', function (err) {
                if (err) {
                    reject(err);
                }
                else {
                    let request = new Request(cmd, function (err, rowCount, rows) {
                        if (err) {
                            reject(err);
                        }
                        else {
                            resolve(rows);
                        }
                        p.connection.close();
                    })
                    p.connection.execSql(request);

                }
            })
        })
        var data = {
            Data: null,
            IsSuccess: true,
            Msgs: []
        }
        try {
            console.time(url)
            var rs = await promise;
            console.timeEnd(url)   
            data.Data=[];
            //console.time(url+'data')
            rs.forEach(function(arr){
                var _obj={ };
                arr.forEach(function(obj){
                    _obj[obj.metadata.colName]=obj.value;
                });
                data.Data.push(_obj);
            })   
            //console.timeEnd(url+'data')        
            return data;
        }
        catch (e) {
            data.IsSuccess = false;
            data.Msgs.push(e);
            return data;
        } 
    }
    _query(cmd) {
        var p = this;
        return new Promise((resolve, reject) => {
            p.connection.on('connect', function (err) {
                if (err) {
                    reject(err);
                }
                else {
                    let request = new Request(cmd, function (err, rowCount, rows) {
                        if (err) {
                            reject(err);
                        }
                        else {
                            resolve(rows);
                        }
                        p.connection.close();
                    })
                    p.connection.execSql(request);

                }
            })
        })
    }
}

module.exports = DBHelper;

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="./jquery-3.1.0.js"></script>
    <title>Document</title>
</head>

<body>
    <button id="btn1">click me</button>
    <button id="btn2">click me</button>
    <script>
        var ajax = new XMLHttpRequest();
        var btn1 = document.getElementById('btn1');
        var btn2 = document.getElementById('btn2');
        var i=1,j=1;
        btn1.addEventListener('click', function () {            
            /*ajax.open('Get', 'ooo', true);
            ajax.onreadystatechange=processResponse;
            ajax.send();*/
            $.ajax({
                type: 'Get',
                url: 'ooo'+i+'_'+Math.random(),
                dataType: 'json',
                success: function (data) {
                   console.log(data)
                    
                },
                
            });
            i++
        })
         btn2.addEventListener('click', function () {            
            /*ajax.open('Get', 'ooo', true);
            ajax.onreadystatechange=processResponse;
            ajax.send();*/
            $.ajax({
                type: 'Get',
                url: 'oo',
                dataType: 'json',
                success: function (data) {
                   console.log(data)
                    
                },
                
            });
        })
        function processResponse() {
            //响应完成且响应正常
            if (ajax.readyState == 1) {
                console.log("XMLHttpRequest对象开始发送请求");
                console.log('--------------------------------------------------------------');
            } else if (ajax.readyState == 2) {
                console.log("XMLHttpRequest对象的请求发送完成");
                console.log('--------------------------------------------------------------');
            } else if (ajax.readyState == 3) {
                console.log("XMLHttpRequest对象开始读取服务器的响应");
                console.log('--------------------------------------------------------------');
            } else if (ajax.readyState == 4) {
                console.log("XMLHttpRequest对象读取服务器响应结束");
                console.log('--------------------------------------------------------------');
                if (ajax.status == 200) {
                    //信息已经成功返回,开始处理信息
                    //先捕获下所有的请求头
                    var headers = ajax.getAllResponseHeaders();
                    console.log(headers);
                    console.log('--------------------------------------------------------------');
                    //得到服务器返回的信息
                    var infor = ajax.responseText;
                     console.log(infor);
                } else {
                    alert("所请求的服务器端出了问题");
                }
            }
        }
    </script>
</body>

</html>

结果: untitled2.pnguntitled3.png

这只是查询不同表的情况,如果是查询同一张表的情况,在chrome下可以看到在stalled状态下等待很久,求解? 数据库是sql server 2008r2,连接模块是tedious


Viewing all articles
Browse latest Browse all 14821

Trending Articles