• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

如果NodeJS API服务失败,如何重新启动?

node.js 来源:FR STAR 16次浏览

我有类似的代码的NodeJS:如果NodeJS API服务失败,如何重新启动?

cluster.js

'use strict'; 

const cluster = require('cluster'); 
var express = require('express'); 
const metricsServer = express(); 
const AggregatorRegistry = require('prom-client').AggregatorRegistry; 
const aggregatorRegistry = new AggregatorRegistry(); 
var os = require('os'); 

if (cluster.isMaster) { 
    for (let i = 0; i < os.cpus().length; i++) { 
     cluster.fork(); 
    } 

    metricsServer.get('/metrics', (req, res) => { 
     aggregatorRegistry.clusterMetrics((err, metrics) => { 
      if (err) console.log(err); 
      res.set('Content-Type', aggregatorRegistry.contentType); 
      res.send(metrics); 
     }); 
    }); 

    metricsServer.listen(3013); 
    console.log(
     'Cluster metrics server listening to 3013, metrics exposed on /metrics' 
    ); 
} else { 
    require('./app.js'); // Here it'll handle all of our API service and it'll run under port 3000 
} 

正如你可以在上面的代码中看到我使用的是手动的NodeJS聚类方法,而不是PM2集群,因为我需要通过Prometheus监控我的API。我通常通过pm2 start cluster.js启动cluster.js,但由于某些数据库连接,我们的app.js服务失败,但是cluster.js没有。它显然看起来像我没有处理数据库连接错误,即使我没有处理它。我想知道,

  • 我该如何确保我的app.js和cluster.js总是重新启动,如果它崩溃?

  • 是否有Linux crontab可以放置检查某些端口始终运行(即3000和3013)? (如果这是一个好主意,我很感激,如果你能提供给我的代码,我没有太多熟悉Linux)

  • 或者,我可以部署其他的NodeJS API检查某些服务正在运行,但因为我的API实时并捕获一定量的负载;做这件事我不高兴吗?

任何帮助将不胜感激,提前致谢。

===========解决方案如下:

我最近发现,如果它死了/关闭,我们可以听工人事件,并相应地重新启动它。

下面是代码:

'use strict'; 

const cluster = require('cluster'); 
var express = require('express'); 
const metricsServer = express(); 
var os = require('os'); 

if (cluster.isMaster) { 
for (let i = 0; i < os.cpus().length; i++) { 
    cluster.fork(); 
} 

cluster.on(
     "exit", 
     function handleExit(worker, code, signal) { 

      console.log( "Worker has died.", worker.process.pid); 
      console.log( "Death was suicide:", worker.exitedAfterDisconnect); 

      // If a Worker was terminated accidentally (such as by an uncaught 
      // exception), then we can try to restart it. 
      if (! worker.exitedAfterDisconnect) { 

       var worker = cluster.fork(); 
       // CAUTION: If the Worker dies immediately, perhaps due to a bug in the 
       // code, you can run [from what I have READ] into rapid CPU consumption 
       // as Master continually tries to create new Workers. 

      } 

     } 
    ); 

} else { 
require('./app.js'); 
} 

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)