美文网首页
egg-mysql配置多数据源

egg-mysql配置多数据源

作者: 一个搞前端的大锤哥哥 | 来源:发表于2020-12-30 13:49 被阅读0次

//单个数据源client

//多个数据源clients

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

export default (appInfo: EggAppInfo) => {

  const config = {} as PowerPartial<EggAppConfig>;

  // 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 };

  }

}

相关文章

网友评论

      本文标题:egg-mysql配置多数据源

      本文链接:https://www.haomeiwen.com/subject/yakhoktx.html