2014-02-22 29 views
0

我有這個示例代碼coffescript對於node.js。我想要做的是從S3並行下載大量對象。爲什麼node.js沒有使用所有可用的帶寬?

用戶包含的朋友列表清單,我想盡可能快地下載所有這些朋友。示例代碼等待1秒以模擬花費多少錢下載用戶對象,並且它從S3下載對象以模擬朋友對象的下載。

async = require 'async' 
aws = require 'aws-sdk' 
cluster = require 'cluster' 
config = require './config' 

USERS = 30 
FRIENDS = 300 

class TestSpeed 

    constructor:() -> 
    @s3 = new aws.S3 accessKeyId:config.S3_KEY, secretAccessKey:config.S3_SECRET 

    start: (next) => 
    async.map([0...USERS], @downloadUser, next) 

    downloadUser: (x, next) => 
    console.log "Starting to download user #{x}" 
    setTimeout(
     => 
     console.log "User downloaded" 
     @downloadFriends(next) 
     , 1000 
    ) 

    downloadFriends: (next) => 
    console.log "Starting to download friends" 
    async.map([0...FRIENDS], @downloadFriend, next) 

    downloadFriend: (x, next) => 
    console.log "Starting to download friend #{x}" 
    @s3.getObject Bucket:config.BUCKET, Key:config.UID, (err, data) -> 
     return console.log err if err? 
     console.log "Friend downloaded" 
     next() 

if cluster.isMaster 
    console.log("starting at master process...") 
    cluster.fork() for [0...4] 

console.log "init" 
new TestSpeed().start (err, result) => 
    return console.trace err if err? 
    console.log "OK" 

我希望發生的事情是節點使用所有可用的帶寬,因爲我在4核心機器中創建4個進程。但是我得到的下載速度大約爲50Mbps,通過8個進程可以達到100Mbps(超過可用核心數)。

我認爲node.js使用了所有可用的資源,但CPU和網絡都不能100%工作。我錯過了什麼?

+2

我想你受限於maxSockets。 在您的文件開始處嘗試'require('http')。globalAgent.maxSocket = 1000'。 看看這個問題http://stackoverflow.com/questions/12201513/optimizing-node-js-for-a-large-number-of-outbound-http-requests –

+1

這就是問題所在!我已經使用https://github.com/aws/aws-sdk-js/issues/116 –

+0

更改了AWS中的maxSocket選項。請@alexeyten發表您的評論一個答案,並將其標記爲有效。 –

回答

1

我想你受限於maxSockets。

嘗試require('http').globalAgent.maxSockets = 1000在您的文件的開始。

看看這個問題Optimizing Node.js for a large number of outbound HTTP requests?

+0

這是正確的答案。我按照https://github.com/aws/aws-sdk-js/issues/116方法更改了aws庫的maxSockets限制。 –

相關問題