2016-02-29 106 views
0

用下面的代碼:Nodejs如何使用Restify處理併發請求?

var counter = 0; 
server.get(
    '/test, 
    function(request, response, next) 
    { 
     console.log('Counter', ++counter); 
     next(); 
    } 
); 

如何計數器變量與數個併發連接的影響? Restify(或Node)具有某種連接日射或一組傳入請求?

非常感謝提前。

+2

節點(在正常情況下)只在一個線程上運行應用程序,所以在單個回調中沒有併發問題。 –

+0

@JoachimIsaksson這應該成爲一個答案。 – HeadCode

+0

@HeadCode不是一個節點大師我希望別人做出更完整的答案,以便我沒有一些細節錯誤,我不知道那裏有一個:)沒有看到它一直沒有答案,所以我會盡量寫一些東西,當我一分鐘。 –

回答

1

實際上,restify正在包裝幾個不同的包之一:spdyhttphttps

if (options.spdy) { 
    this.spdy = true; 
    this.server = spdy.createServer(options.spdy); 
} else if ((options.cert || options.certificate) && options.key) { 
    this.ca = options.ca; 
    this.certificate = options.certificate || options.cert; 
    this.key = options.key; 
    this.passphrase = options.passphrase || null; 
    this.secure = true; 

    this.server = https.createServer({ 
     ca: self.ca, 
     cert: self.certificate, 
     key: self.key, 
     passphrase: self.passphrase, 
     rejectUnauthorized: options.rejectUnauthorized, 
     requestCert: options.requestCert, 
     ciphers: options.ciphers 
    }); 
} else if (options.httpsServerOptions) { 
    this.server = https.createServer(options.httpsServerOptions); 
} else { 
    this.server = http.createServer(); 
} 

來源:https://github.com/restify/node-restify/blob/5.x/lib/server.js

這些軟件包管理的要求,這是因爲內restify事件處理的異步特性。 The EventListener calls all listeners synchronously in the order in which they were registered.。在這種情況下,restify是監聽程序,並將按收到的順序處理請求。

縮放比例

話雖這麼說,像restify web服務器往往通過釋放他們背後像nginx代理多個進程放大。在這種情況下,nginx將在進程之間拆分傳入請求,從而有效地允許Web服務器處理更大的併發負載。

Node.js的限制

最後,一定要記住,這是全部由Node.js的行爲限制由於應用程序在單個線程上運行,因此可以在執行緩慢的同步請求時有效地阻止所有請求。

server.get('/test', function(req, res, next) { 
    fs.readFileSync('something.txt', ...) // blocks the other requests until done 
}); 
+0

糾正我,如果我錯了:Nodejs使用每個服務器實例的連接隊列。它是單線程的,但是可以升級,因爲多個實例可以在相同或另一臺機器上運行相同的應用程序,動態平衡負載(如果使用羣集模塊或類似的東西)。 我是對的? –

+0

Node.js不使用每個服務器實例的連接隊列。這將是每個應用程序實例。通常,像'nginx'這樣的東西將用於縮放。它現在看起來像'cluster'模塊現在是穩定的:https://nodejs.org/api/cluster.html。乍一看,它似乎僅限於在單個服務器上進行擴展。 – bitsoflogic