剛剛有小朋友問B老師:egg怎麼配置多個數據源呀,網上那些死勁兒很差用
那B老師給你們解釋下怎麼配置
通常不會配置多數據源的朋友是沒有看清官網關於配置多數據源的代碼(有點坑)mysql
單個數據源config.mysql裏面的client不帶s
多個數據源config.mysql裏面的client帶sgit
//單個數據源client
//多個數據源clientsgithub
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, }; };
而後去服務裏面使用數據庫sql
// 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 }; } }