刚刚有小朋友问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<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.tsimport { 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 }; }}