前言
上一篇文章我们介绍Egg项目的初始化和第一个接口的尝试,但是做为一个后端的接口项目,显然不能直接返回静态的数据,这个时候我们就需要引入mysql和redis来做数据存储。本篇文章就会介绍一下Egg项目如何连接和使用mysql和redis。
提示:以下是本篇文章正文内容,下面案例可供参考
一、连接和使用Mysql?
1.1 引入egg-sequelize插件
npm install --save egg-sequelize mysql2
编辑项目的config/plugin.js文件,,添加以下内容
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
sequelize: {
enable: true,
package: 'egg-sequelize',
},
}
在config/config.default.js添加好自己本地/远端mysql服务的配置信息:
config.sequelize = {
dialect: 'mysql',
host: '127.0.0.1',//服务ip
port: 13306,//服务端口
database: 'your database',
username: 'your username',
password: 'your password',
};
在app/目录下创建model文件夹,在model文件夹下增加数据表文件:
// 示例app/model/category.js
'use strict';
module.exports = app => {
const { STRING, INTEGER, BOOLEAN } = app.Sequelize;
const Category = app.model.define('tbl_category', {
id: { type: INTEGER, primaryKey: true, field: 'c_id', autoIncrement: true },
name: { type: STRING(50), allowNull: false, field: 'c_name', Comment: '分类名称' },
desc: { type: STRING(50), field: 'c_desc', Comment: '分类描述' },
enable: { type: BOOLEAN, field: 'c_enable', Comment: '分类状态' },
}, {
}, {
// 在mysql的数据表名
tableName: 'tbl_category',
Comment: '分类表',
//开启时间戳,会自动添加 createdAt 和 updatedAt 字段
timestamps: true,
});
return Category;
};
此时启动项目发现数据库不会自动生成我们新创建的数据表,这个时候需要在agent.js增加启动自动创建数据表的逻辑:
// 在agent.js文件中新增下面这段代码,如果没有agent.js文件,可以自己创建一个
'use strict';
module.exports = agent => {
agent.beforeStart(async function() {
await agent.model.sync();
});
};
启动项目我们就发现控制台会出现这段输出:
接下来我们就可以在service层进行数据库操作了:
'use strict';
const Service = require('egg').Service;
class CategoryService extends Service {
async findAll(data, option = {}) {
const { ctx } = this;
return await ctx.model.Category.findAll({ where: data, ...option });
}
}
module.exports = CategoryService;
二、连接和使用Redis?
1.引入egg-redis插件
npm install --save egg-redis
编辑项目的config/plugin.js文件,,添加以下内容
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
redis: {
enable: true,
package: 'egg-redis',
},
}
在config/config.default.js添加好自己本地/远端redis服务的配置信息:
config.redis = {
client: {
port: 6379, // Redis 端口号
host: '127.0.0.1', // Redis 主机名
password: '123456', // Redis 密码(如果有的话)
db: 0, // Redis 数据库索引
},
}
启动项目就可以尝试在项目的controller和service层对redis进行操作:
// 示例
async index(){
await this.app.redis.set('test',1)
const res = await this.app.redis.get('test')
this.ctx.body={
code:0,
data:res
}
}
总结
经过上面的学习和操作我们就可以轻易的在egg项目里面使用mysql和redis对数据进行存储和读取了,想要进一步学习的话,可以查看egg-sequelize和egg-redis的文档和源码来了解更多丰富的操作方法。