节点+mysql+套接字io+协议\连接\丢失

aoyhnmkz  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(231)

版本:
节点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. 错误。我试过这个和这个。它们似乎不起作用。
连接不是第一次建立的,但是如果我在错误事件上设置了间隔,并在一段时间后尝试重新连接,它会连接。。但是一些新的连接对象是如何不被使用的。。
我换了我的分行。。连接工作完美无瑕。其他团队成员同时工作,他们的连接没有任何问题。所以我猜这与我实现通知的方式有关。
以下是我的文件:
//插座.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);
}

//服务.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();

我的数据库文件目前[经过大量调试]如下所示。在通知模型中从导入中注解掉这个文件可以解决这个错误。
//数据库.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;

感谢您的帮助。

txu3uszq

txu3uszq1#

你也可以在你的代码中使用pm2他们可以很容易地处理这个问题。
在终端/shell中使用此命令 pm2 init //they provide you ecosystem.config.js 修改生态系统文件以满足您的需要
将pm2作为依赖项添加到项目中 npm install pm2 or yarn add pm2 在package.json中,修改start scrip。
如下所示。

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

最后

npm start
hi3rlvi2

hi3rlvi22#

回答我自己的问题。。我用连接池解决了。。
//数据库.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');
    }
});

相关问题