英文:
Reconnect logic on connection close in X DevAPI of MySql using @mysql/xdevapi module in Node.js
问题
I am using X DevAPI of MySql v8.0.33 using @mysql/xdevapi v8.0.33.
I have reconnect logic added but that is not working. Here is that code.
const mysqlx = require('@mysql/xdevapi')
async function createSession() {
  try {
    const session = await mysqlx.getSession({
      user: 'your_user',
      password: 'your_password',
      host: 'your_host',
      port: 33060, // default MySQL X Protocol port
    });
    // Handle connection close by reconnecting the session
    session['_client']['_stream'].on('close', () => {
      console.log('Connection closed. Reconnecting...');
      createSession(); // Re-establish the session
    });
    // Use the session for your database operations
    // ...
  } catch (error) {
    console.error('Error connecting to MySQL:', error);
  }
}
// Create the initial session
createSession();
I am getting error
TypeError: Cannot read properties of undefined (reading '_stream')
This error means that session['_client'] is undefined.
What is wrong with my reconnect logic?
英文:
I am using X DevAPI of MySql v8.0.33 using @mysql/xdevapi v8.0.33.
I have reconnect logic added but that is not working. Here is that code.
const mysqlx = require('@mysql/xdevapi')
async function createSession() {
  try {
    const session = await mysqlx.getSession({
      user: 'your_user',
      password: 'your_password',
      host: 'your_host',
      port: 33060, // default MySQL X Protocol port
    });
    // Handle connection close by reconnecting the session
    session['_client']['_stream'].on('close', () => {
      console.log('Connection closed. Reconnecting...');
      createSession(); // Re-establish the session
    });
    // Use the session for your database operations
    // ...
  } catch (error) {
    console.error('Error connecting to MySQL:', error);
  }
}
// Create the initial session
createSession();
I am getting error
TypeError: Cannot read properties of undefined (reading '_stream')
This error means that session['_client'] is undefined.
What is wrong with my reconnect logic?
答案1
得分: 1
正如您提到的,session['_client'] 未定义也不可用。我猜你可以通过 session.getConnection_().getClient().getConnection() 获取套接字引用,但这是一个内部 API,并且容易在没有通知的情况下发生变化,所以我可能不建议使用它。相反,你可以创建一种装饰器,包装你的工作流程,并在没有可用连接时创建连接。
免责声明:我是 MySQL X DevAPI Connector for Node.js 的首席开发人员
英文:
As you mention, session['_client'] is not defined nor available. I guess you can get a socket reference with session.getConnection_().getClient().getConnection(), however this is an internal API and is prone to breaking changes without notice, so I would probably not recommend it. Instead, you can have some kind of decorator that wraps your workflows and creates a connection if one is not available.
Disclaimer: I'm the lead developer of the MySQL X DevAPI Connector for Node.js
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论