我正在开发一个 Node.js 项目,该项目使用 Sequelize 连接到 MariaDB 数据库。连接在我的本地环境中工作正常,但是当我尝试连接到 AWS RDS 上托管的 MariaDB 数据库时,它失败了。
我已验证 AWS RDS 连接可以使用 MySQL Workbench 正常工作,但我的 Node.js 项目抛出以下错误:
无法连接到数据库:SequelizeConnectionError:(conn = 1690,no:45012,SQLState:08S01)连接超时:1001ms后无法创建套接字
我尝试看起来像这样:
const dbConfig = require('../config/dbConfig');
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
port: dbConfig.PORT,
dialect: "mariadb",
operatorsAliases: 0,
define: {
freezeTableName: true // it's default behavior is to modified table name automatic, so we restrict it with this param
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
sequelize.authenticate()
.then(() => {
console.log('DB Connected...');
})
.catch((error) => {
console.error(`Unable to connect to the database: ${error}`);
})
您的 RDS 实例是否可公开访问?
要启用公共访问,您可以转到修改,然后在连接性下转到其他配置并将公共访问设置为“公共可访问”。 另外,当询问时,请立即进行更改,而不是在下一个计划中 - 您需要等待一两分钟,直到修改完成才能访问实例。
确保您已创建数据库(因为默认情况下没有)。如果您没有提供
null
作为 dbConfig.DB 值:
const dbConfig = require('./config/dbConfig');
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize(null, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
port: dbConfig.PORT,
dialect: 'mariadb',
dialectOptions: {
// Your additional options here
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
sequelize.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
您应该能够看到以下消息:
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.