【问题标题】:Node + Mysql + Socket IO + PROTOCOL_CONNECTION_LOSTNode + Mysql + Socket IO + PROTOCOL_CONNECTION_LOST
【发布时间】:2018-12-13 22:09:06
【问题描述】:

版本:

节点 JS:7.2.1

快递:4.15.3

MySQL NPM:2.14.1

套接字 IO:2.1.1

我们刚刚在我们的应用程序中引入了套接字,试图让通知运行。但从那时起,我的数据库就无法连接。

我不断收到PROTOCOL_CONNECTION_LOST : Connection lost: The server closed the connection. 错误。我试过thisthis。它们似乎不起作用。

第一次没有建立连接,但是如果我在错误事件上设置Interval并在一段时间后尝试重新连接,它确实连接了..但是有些新的连接对象没有使用..

我切换了我的分支.. 连接完美无缺。还有其他团队成员同时工作,他们的连接没有任何问题。所以我猜这与我实现通知的方式有关。

以下是我的文件:

//socket.js

import server from './../../server.js';
import SocketIO from "socket.io";
import nconf from "nconf";
import eventService from "../../events/service.js";

module.exports.initSocket = (IO) => {
    let event = eventService(IO);
    let notificationEmissionInterval = nconf.get('NOTIFICATION_INTERVAL_MILLISECONDS');

    IO.on("connection", (socket) => {
        setInterval(() => {
            event.emitNotifications(socket);
        }, notificationEmissionInterval);
    });
};

if (server) {
    let IO = new SocketIO(server);
    module.exports.initSocket(IO);
}

//service.js

import path from 'path';
import logger from '../config/lib/logger.js';
import notificationController from "../module/notification/controller/notification.controller.js";

module.exports = (IO) => {
    let emitNotifications = (socket) => {   
        notificationController.getUnreadNotifications(params)
        .then((notifications) => {
        //Do something
        )
    };

    return {
        emitNotifications: emitNotifications,
    }
};

//模型.js

import connection from '../../../config/lib/db.js';
import logger from 'logger';
import Promise from 'bluebird';

class NotificationModel {

    getUnreadNotifications = () => {
        return new Promise((resolve, reject) => {
            let query = `CALL GetUnreadNotification()`;
            connection.query(query, (err, result) => {
                if (err) {
                    logger.error('Sql error in NotificationModel.getUnreadNotifications : ', err);
                    reject(err);
                }
                else {
                    logger.info('Unread notifications fetched successfully');
                    resolve(result);
                }
            });
        });
    };

}
export default new NotificationModel();

我的数据库文件目前 [经过大量调试] 如下所示。从通知模型中的导入中注释掉此文件可解决该错误。

//db.js

import mysql from 'mysql';
import nconf from 'nconf';
import logger from './logger.js';
import path from 'path';

nconf.argv()
    .env()
    .file({
        file: path.resolve('./config.json')
    });

let dbConfig = {
    "host": nconf.get('MYSQL_HOST'),
    "port": nconf.get('MYSQL_PORT'),
    "user": nconf.get('MYSQL_USER'),
    "password": nconf.get('MYSQL_PASSWORD'),
    "database": nconf.get('MYSQL_DATABASE'),
    "stringifyObjects":true,
    "multipleStatements": true,
    "dateStrings" : 'DATETIME',
    "connectTimeout" : 60000
};

function connectToDatabase() {
    logger.info('Trying to connect to the database');
    let _conn = mysql.createConnection(dbConfig);

    _conn.connect((err) => {
        if (err) {
            logger.error('Error connecting to the database');
            logger.debug(err.code + ' : ' + err.message);
            setTimeout(connectToDatabase, 3000);
        }
        else {
            logger.info('Connected to the database via threadId : ' + _conn.threadId);
            return _conn;
        }
    });

    _conn.on('error', (err) => {
        logger.error('Error connecting to the database');
        logger.debug(err.code + ' : ' + err.message);
        setTimeout(connectToDatabase, 3000);
    });
}

let connection = connectToDatabase();

export default connection;

感谢任何帮助。

【问题讨论】:

    标签: mysql socket.io connection database-connection


    【解决方案1】:

    回答我自己的问题..我使用连接池解决了..

    //db.js

    let pool = mysql.createPool(dbConfig);
    
    pool.on('connection', function (_conn) {
        if (_conn) {
            logger.info('Connected the database via threadId %d!!', _conn.threadId);
            _conn.query('SET SESSION auto_increment_increment=1');
        }
    });
    

    【讨论】:

      【解决方案2】:

      您也可以在代码中使用 pm2,它们可以轻松处理此问题。

      1. 在终端/shell 中使用此命令

        pm2 init //they provide you ecosystem.config.js

      2. 修改生态系统文件以满足您的需求

      3. 将 pm2 添加为项目的依赖项

        npm install pm2 or yarn add pm2

      4. 在您的 package.json 中,修改您的启动脚本。

      如下所示。

      {
         "scripts": {
                  "start": "pm2-runtime start ecosystem.config.js --env production"
                  }
      }
      

      最后

      npm start
      

      【讨论】:

        猜你喜欢
        • 2014-10-18
        • 2016-02-19
        • 2017-08-07
        • 2015-12-24
        • 2013-10-05
        • 2013-04-20
        • 2021-04-29
        • 1970-01-01
        • 2015-06-14
        相关资源
        最近更新 更多