当前位置: 首页 > 后端技术 > Node.js

egg-mysql配置多数据源

时间:2023-04-03 11:26:18 Node.js

刚才有小朋友问B君:egg如何配置多数据源?网上说的不好用,B君给大家讲解一下怎么配置。一般不配置多数据源的朋友没有看过官网关于配置多数据源的内容。源代码(有点坑)单数据源config.mysql中的client没有s多数据源config.mysql中的client有s//单数据源client//多数据源clientimport{EggAppConfig,EggAppInfo,PowerPartial}from"egg";exportdefault(appInfo:EggAppInfo)=>{constconfig={}asPowerPartial;}//从框架/插件覆盖配置//用于cookie签名密钥,应该更改为您自己的并保持安全config.keys=appInfo.name+"_1606967424562_9661";//在这里添加你的egg配置config.middleware=[];//在这里添加你的特殊配置constbizConfig={sourceUrl:`https://github.com/eggjs/examples/tree/master/${appInfo.name}`,};//连接服务器config.mysql={//数据库配置//单数据源客户端//client:{//host//host:"localhost",//port//port:"3306",//username//user:"root",//密码//password:"root",//dabase//database:"egg",//},//多个数据源clientsclients:{db1:{//hosthost:"localhost",//portport:"3306",//usernameuser:"root",//passwordpassword:"root",//databasedatabase:"egg",},db2:{//hosthost:"localhost",//port端口:"3306",//usernameuser:"root",//passwordpassword:"root",//databasedatabase:"hubeiwh",},},//所有数据库配置的默认值default:{},//加载到app中,默认是open//加载到应用程序,默认是打开app:true,//loadintoagent,defaultisclose//加载到agent,defaultvalueis"close"agent:false,};//返回的配置将合并到EggAppConfigreturn{...config,...bizConfig,};};然后在service中使用数据库//app/service/Test.tsimport{Service}from"egg";/***TestService*/exportdefaultclassTestextendsService{/***查询egg中的username表库*@param{string}name用户名*/publicasyncname(name:string){constdata:any=awaitthis.app.mysql//使用db1数据库query.get("db1").query(`SELECT*FROMUSERNAMEWHEREname='${name}'`);返回{数据};}/***查询hubeiwh库中的username表*@param{number}entPidenterpriseid*/publicasyncentprise(entPid:number){constdata:any=awaitthis.app.mysql//使用db2数据库查询.get("db2").get("cim_enterprise",{enterprisepid:entPid});返回{数据};}}