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