📌  相关文章
📜  检查 Node.js MySQL 服务器是否处于活动状态

📅  最后修改于: 2022-05-13 01:56:56.261000             🧑  作者: Mango

检查 Node.js MySQL 服务器是否处于活动状态

我们将看到如何检查托管我们的 MySQL 数据库的服务器是否处于活动状态。

句法:

database_connection.ping(callback);

模块:

  • 节点JS
  • ExpressJS
  • MySQL

    设置环境和执行:

  1. 创建项目

    npm init

  2. 安装模块

    npm install express
    npm install mysql

    文件结构:

  3. 创建服务器

    index.js
    const express = require("express");
    const database = require('./sqlConnection');
      
    const app = express();
      
    app.listen(5000, () => {
      console.log(`Server is up and running on 5000 ...`);
    });


    sqlConnection.js
    const mysql = require("mysql");
      
    let db_con  = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: ''
    });
      
    db_con.connect((err) => {
        if (err) {
          console.log("Database Connection Failed !!!", err);
        } else {
          console.log("connected to Database");
        }
    });
      
    module.exports = db_con;


    Javascript
    const express = require("express");
    const database = require('./sqlConnection');
      
    const app = express();
      
    app.listen(5000, () => {
      console.log(`Server is up and running on 5000 ...`);
    });
      
    app.get("/getMysqlStatus", (req, res) => {
          
        database.ping((err) => {
            if(err) return res.status(500).send("MySQL Server is Down");
              
            res.send("MySQL Server is Active");
        })
    });


  4. 创建和导出数据库连接对象

    sqlConnection.js

    const mysql = require("mysql");
      
    let db_con  = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: ''
    });
      
    db_con.connect((err) => {
        if (err) {
          console.log("Database Connection Failed !!!", err);
        } else {
          console.log("connected to Database");
        }
    });
      
    module.exports = db_con;
    
  5. 创建路由以检查 mysql 服务器是否处于活动状态。

    app.get("/getMysqlStatus", (req, res) => {
      
      database.ping((err) => {
        if(err) return res.status(500).send("MySQL Server is Down");
          
        res.send("MySQL Server is Active");
      })
    });
    

    完整的 index.js 文件:

    Javascript

    const express = require("express");
    const database = require('./sqlConnection');
      
    const app = express();
      
    app.listen(5000, () => {
      console.log(`Server is up and running on 5000 ...`);
    });
      
    app.get("/getMysqlStatus", (req, res) => {
          
        database.ping((err) => {
            if(err) return res.status(500).send("MySQL Server is Down");
              
            res.send("MySQL Server is Active");
        })
    });
    
  6. 运行服务器

    node index.js
  7. 输出:将此链接放入浏览器http://localhost:5000/getMysqlStatus

    • 如果服务器未激活,您将在浏览器中看到以下输出:
    MySQL Server is Down

    • 如果服务器处于活动状态,您将在浏览器中看到以下输出
    MySQL Server is Active