【问题标题】:how to make cpu usage to 100% in nodejs如何在nodejs中使cpu使用率达到100%
【发布时间】:2015-01-12 23:15:21
【问题描述】:

我有一个 nodejs 服务器。我想在这个服务器上测试 node-toobusy 模块。 我编写了一个客户端代码同时命中该服务器以使 cpu 使用率达到 100%,但我仍然无法使该模块工作。 PFB 服务器代码

var toobusy = require('toobusy'),
express = require('express');

var app = express();

// middleware which blocks requests when we're too busy app.use(function(req, res, next) {
 if (toobusy()) {
res.send(503, "I'm busy right now, sorry."); console.log("hi");
 } else {
 next();
console.log("hi");
 }
});

console.log("hi");
app.get('/', function(req, res) {
// processing the request requires some work!
var i = 0;
while (i < 1e5) i++;
res.send("I counted to " + i);
console.log("hi");
});

var server = app.listen(3005);

process.on('SIGINT', function() {
server.close();
// calling .shutdown allows your process to exit normally  toobusy.shutdown();
process.exit();
});

关于如何使用该模块的任何想法都会非常有帮助。

【问题讨论】:

  • 试着数到无穷大:)

标签: node.js cpu-usage node-modules


【解决方案1】:

您只是在应用启动时检查服务器是否太忙()。

作为中间件的用法见下文:

app.use(function(req, res, next) {
    if (toobusy()) {
        res.send(503, "I'm busy right now, sorry.");
    } else {
        next();
    } 
});

这将检查传入的每个请求,并且仅在当前负载低于最大阈值时调用 next()。

您还可以设置最大延迟阈值:

toobusy.maxLag(10);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2018-04-16
    • 2020-10-06
    • 2015-04-05
    • 2015-07-01
    相关资源
    最近更新 更多