egg-mysql配置多数据源

刚刚有小朋友问B老师:egg怎么配置多个数据源呀,网上那些死劲儿不好用
那B老师给大家解释下怎么配置
一般不会配置多数据源的朋友是没有看清官网关于配置多数据源的代码(有点坑)

单个数据源config.mysql里面的client不带s
多个数据源config.mysql里面的client带s

//单个数据源client
//多个数据源clients

import { EggAppConfig, EggAppInfo, PowerPartial } from "egg";

export default (appInfo: EggAppInfo) => {
  const config = {} as PowerPartial;

  // override config from framework / plugin
  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + "_1606967424562_9661";

  // add your egg config in here
  config.middleware = [];

  // add your special config in here
  const bizConfig = {
    sourceUrl: `https://github.com/eggjs/examples/tree/master/${appInfo.name}`,
  };
  //连接服务器
  config.mysql = {
    //database configuration
    //单个数据源client
    //client: {
        //host
        //host: "localhost",
        //port
        //port: "3306",
        //username
        //user: "root",
        //password
        //password: "root",
        //database
        //database: "egg",
    //},
    //多个数据源clients
    clients: {
      db1: {
        //host
        host: "localhost",
        //port
        port: "3306",
        //username
        user: "root",
        //password
        password: "root",
        //database
        database: "egg",
      },
      db2: {
        //host
        host: "localhost",
        //port
        port: "3306",
        //username
        user: "root",
        //password
        password: "root",
        //database
        database: "hubeiwh",
      },
    },
    // 所有数据库配置的默认值
    default: {},
    //load into app,default is open //加载到应用程序,默认为打开
    app: true,
    //load into agent,default is close //加载到代理中,默认值为“关闭”
    agent: false,
  };
  // the return config will combines to EggAppConfig
  return {
    ...config,
    ...bizConfig,
  };
};

然后去服务里面使用数据库

// app/service/Test.ts
import { Service } from "egg";

/**
 * Test Service
 */
export default class Test extends Service {
  /**
   * 查询egg库里面username表
   * @param {string} name 用户名称
   */
  public async name(name: string) {
    const data: any = await this.app.mysql
      //使用db1数据库查询
      .get("db1")
      .query(`SELECT * FROM USERNAME WHERE name = '${name}'`);
    return { data };
  }
  /**
   * 查询hubeiwh库里面username表
   * @param {number} entPid 企业id
   */
  public async entprise(entPid: number) {
    const data: any = await this.app.mysql
      //使用db2数据库查询
      .get("db2")
      .get("cim_enterprise", { enterpid: entPid });
    return { data };
  }
}

你可能感兴趣的:(node.js,eggjs)