背景:
随着用户量增多,mysql连接数过多,为解决此问题,配置mysql主从为有效的解决办法。
以下为node egg框架的主从配置
走起:
1、安装插件
npm i --save egg-sequelize
2、在 config/plugin.js 启用插件
exports.sequelize = {
enable: true,
package: 'egg-sequelize'
}
3、egg根目录配置文件 ./config/config.default.js
config.sequelize = {
datasources: [
{
delegate: 'model',
baseDir: 'model',
dialect: 'mysql',
database: 'demo',
timezone: '+08:00',
replication: {
read: [
{ host: '127.0.0.1', username: 'root', port: 3306, password: 'root' }, //mysql从库
{ host: '127.0.0.1', username: 'root', port: 3307, password: 'root' } //mysql从库
],
write: { host: '127.0.0.1', username: 'root', port: 3308, password: 'root' } //mysql主库看
},
define: {
underscored: true,
freezeTableName: true
}
}
]
}
4、应用调用
//原生sql调用
let sql = `select * from user limit 10`
let data = await this.app.model.query(sql, {raw: true, type: 'SELECT'})
//其他调用 略..