3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

request-promise 接続数管理

Last updated at Posted at 2018-07-11

キャパシティプランニングの観点からソケットに最大値を設定したい場合がある

その場合以下のようなヘルパクラスを作成して管理する

const http = require('http')
const https = require('https')

class MyAgent {
    constructor(max) {
        this.http = new http.Agent(),
        this.https = new https.Agent(),
        this.http.maxSockets = max
        this.https.maxSockets = max
    }   
    get(uri) {
        if(uri.match("https://")){
            return this.https
        }else if(uri.match("http://")){
            return this.http
        }   
    }   
}   

上記で作ったヘルパクラスを以下のようにrequest-promiseのオプションパラメータであるpoolにいれると最大ソケット数を制限できる

下記のサンプルでは五つ同時アクセスをしているがソケット数は1個に制限できている

const rp = require('request-promise')
const myAgent = new MyAgent(1)

const get = async() => {
    const uri = "http://example.com"
    const opt = {
        uri : uri,
        method: "GET",
        timeout: 10 * 1000,
        pool: myAgent.get(uri),
    }
    const result = { success: null, error: null, time: 0 }
    const begintime = process.uptime()
    try{
        result.success = await rp(opt)
    }catch(e){
        result.error = e
    }
    const endtime = process.uptime()
    result.time = endtime - begintime
    return result
}

get().then(console.log)
get().then(console.log)
get().then(console.log)
get().then(console.log)
get().then(console.log)
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?