eggjs中egg-mysql不支持mysql集群,代码修改为支持集群

说明:暂不支持egg-mysql动态数据源,用到动态数据源请自行修改。欢迎各位大佬指导。。。

   

1.找到node_modules/ali-rds/lib/client.js,

RDSClient修改如下:
 
function RDSClient(options) {
  if (!(this instanceof RDSClient)) {
    return new RDSClient(options);
  }
  Operator.call(this);
  let configObj = JSON.stringify(options);
  let len = configObj.match(/\{/g);
  if (len.length > 1) {
    delete options.connectionLimit;
    delete options.database;
    let poolCluster = mysql.createPoolCluster({
      removeNodeErrorCount: 1,
      defaultSelector: "RR" //RR,RANDOM,ORDER
    });
    for (let node in options) {
      poolCluster.add(`${node}`, options[`${node}`]);
    }
    this.pool = poolCluster.of('*', 'RR');
    console.log('<<<<<<----mysql createPoolCluster---->>>>>>>', options, len)
  } else {
    this.pool = mysql.createPool(options);
    console.log('<<<<<<-----mysql createPool--->>>>>>>', options, len)
  }
  [
    'query',
    'getConnection',
  ].forEach(method => {
    this.pool[method] = promisify(this.pool[method]);
  });
}

 2./node_modules/egg-mysql/lib/mysql.js,修改如下

   

'use strict';

const assert = require('assert');
const rds = require('ali-rds');

let count = 0;

module.exports = app => {
  app.addSingleton('mysql', createOneClient);
};

function createOneClient(config, app) {
  const client = rds(config);
  app.beforeStart(function* () {
    const rows = yield client.query('select now() as currentTime;');
    const index = count++;
    app.coreLogger.info(`[egg-mysql] instance[${index}] status OK, rds currentTime: ${rows[0].currentTime}`);
  });
  return client;
}

猜你喜欢

转载自www.cnblogs.com/qiyc/p/12966913.html