mysql多数据源_egg-mysql配置多数据源
//單個數據源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 };
}
}
總結
以上是生活随笔為你收集整理的mysql多数据源_egg-mysql配置多数据源的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: React Native开发指南-在原生
- 下一篇: HA集群实现原理 切换 JAVA_HA(