4
4

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.

node.jsにリミッターを設定したい

4
Last updated at Posted at 2013-07-31

使いどころ

人間ではない相手が無茶なリクエストをしてくることがあるので
そういったリクエスト数に一定の制限を設けたいときに使うかなぁ

例ではCPU処理をあげてるけど実際にはMYSQLとかMYSQLとかMYSQLだろうなぁ

:limitter.js
var createLimitter = module.exports = function(max, reset_sec){
    var reset_time = process.uptime() + reset_sec;
    var count = 0;
    return function(){
        if(process.uptime() >= reset_time){
            reset_time = process.uptime() + reset_sec;
            count = 0;
        }
        if(count >= max){
            return false;
        }
        count++;
        return true;
    };
};
:worker.js
var createLimitter = require('./limitter');
var check = createLimitter(20, 1); // 秒間20回まで

var heavy_work = function(){
    if(!check()){
        return false;
    }
    cpu_heavy_calc();
    return true;
}
4
4
1

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?