MySQL Forums
Forum List  »  Connector/Node.js

Re: Reconnect logic on connection close in X DevAPI of MySql using @mysql/xdevapi module in Node.js
Posted by: Shelly Megan
Date: September 04, 2023 03:55AM

To implement a reconnect logic in MySQL X DevAPI while using Node.js without directly accessing internal properties, you should use the built-in event handling provided by the library. Here's how you can modify your code to achieve that:
javascriptCopy 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
});

// Use the session for your database operations in Node.js
// ...

// Handle unexpected disconnections and automatically reconnect in Node.js
session.on('close', () => {
console.log('Connection closed. Reconnecting...');
createSession(); // Re-establish the session
});

} catch (error) {
console.error('Error connecting to MySQL in Node.js:', error);
}
}

// Create the initial session in Node.js
createSession();
This approach, tailored for Node.js, uses event handling to detect unexpected disconnections and automatically reconnect without directly accessing internal properties, as recommended in the MySQL X DevAPI library.

Options: ReplyQuote


Subject
Written By
Posted
Re: Reconnect logic on connection close in X DevAPI of MySql using @mysql/xdevapi module in Node.js
September 04, 2023 03:55AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.