首页 > 解决方案 > Node.js 在不使用时休眠,最初需要很长时间才能响应

问题描述

我已将 Node.js 部署为从数据库返回数据以用于 React 单页应用程序的解决方案。该解决方案就像一个魅力,一切都很好。然而,我发现发生的事情(并且找不到解决方案)是 Node.js 在几分钟后未使用时似乎进入睡眠状态。一旦 React 站点再次被“激活”——加载的页面需要访问数据库,Node.js 似乎会唤醒并返回数据,这需要一两分钟的时间。然后,它通过及时服务进一步的呼叫来发挥应有的作用。

在线解决方案谈论 Windows 机器进入睡眠状态,但这里不是这种情况,因为我当时连接到机器。即使在我的开发 Windows 10 机器上本地部署,停止和重新启动 Node 服务器也比等待它响应更快。

开发和生产机器是基于 Windows 10 的机器,具有 64G 内存,使用 Mysql 数据库。

我无法找到其他解决方案来解决这个问题。

下面是 Node 启动服务器并侦听端口 3002 以获取传入请求的 App.js(或 server.js)文件:

const express = require("express");
const ipfilter = require('express-ipfilter').IpFilter
const bodyParser = require("body-parser");
const cors = require('cors');
const app = express();

app.use(cors());

// Whitelist the following IPs
const ips = ['localhost']

// parse requests of content-type: application/json
app.use(bodyParser.json());

// parse requests of content-type: application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// Create the server
//app.use(ipfilter(ips, { mode: 'allow' }))

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to Server Application." });
});

require("./routes/customer.routes.js")(app);
require("./routes/data.routes.js")(app);

// set port, listen for requests
 app.listen(3002, () => {
  console.log("Server Connection Successful.");
  console.log("Server is running on port 3002.");
}); 

我还建立了与数据库池的连接,认为这可能是以下解决方案:

const connection  = mysql.createPool({
  connectionLimit : dbConfig.CONNECTIONLIMIT,
  host            : dbConfig.HOST,
  user            : dbConfig.USER,
  password        : dbConfig.PASSWORD,
  database        : dbConfig.DB,
  port            : dbConfig.PORT
});

但问题仍然存在。

任何援助将不胜感激。

标签: node.jsreactjs

解决方案


推荐阅读