实现接口API并连接mysql数据库
在 egg 中,提供了 egg-mysql 插件来访问 mysql 数据库。
# 1、安装插件 egg-mysql
npm install egg-mysql -S
1
# 2、在 /app/config/plugin.js 中开启插件:
mysql: {
enable: true,
package: 'egg-mysql',
}
1
2
3
4
2
3
4
# 3、在 /app/config/config.${env}.js 中配置各个环境的数据库连接信息:
# (1)、单数据源:如果我们的应用只需要访问一个 MySQL 数据库实例。
// config/config.default.js
config.mysql = {
// 单数据库信息配置
client: {
// host
host: 'localhost',
// 端口号
port: '3306',
// 用户名
user: 'root',
// 密码
password: '12345678',
// 数据库名
database: 'runoob',
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# (2)、多数据源:如果我们的应用需要访问多个 MySQL 数据源。
// config/config.default.js
config.mysql = {
clients: {
// clientId, 获取client实例,需要通过 app.mysql.get('clientId') 获取
db1: {
// host
host: 'mysql.com',
// 端口号
port: '3306',
// 用户名
user: 'test_user',
// 密码
password: 'test_password',
// 数据库名
database: 'test',
},
db2: {
// host
host: 'mysql2.com',
// 端口号
port: '3307',
// 用户名
user: 'test_user',
// 密码
password: 'test_password',
// 数据库名
database: 'test',
},
// ...
},
// 所有数据库配置的默认值
default: {},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
使用方式:
const client1 = app.mysql.get('db1');
const client2 = app.mysql.get('db2');
1
2
2
# 4、编写 RESTful API 并实现数据库连接
在 /app/controller 下新建 list.js 文件:
'use strict';
const { Controller } = require('egg');
class ListController extends Controller {
async getList () {
const { ctx } = this;
const userId = ctx.request.body.userId
// 其中user表示/app/service下的user.js文件,find表示user.js文件中的find方法
const userInfo = await ctx.service.user.find(userId)
ctx.body = userInfo
}
}
module.exports = ListController;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
在 /app/service 下新建 user.js 文件:
const { Service } = require('egg')
class UserService extends Service {
async find(uid) {
// user_list是表名称
// const user = await this.app.mysql.get('user_list', {user_id: uid})
const user = await this.app.mysql.select('user_list', {
where: {
user_id: uid
}
})
return user
}
}
module.exports = UserService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
在 /app/router.js 文件中配置如下:
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.post('/getList', controller.list.getList)
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
至此,准备工作均已完成,接下来启动项目,启动数据库,在 Postman 中模拟该请求,即可从数据库中获取到 user_id 为 10 的用户:
ps:
编辑 (opens new window)
上次更新: 7/2/2024, 11:06:45 AM