egg手动搭建
- 生成package.json文件
- 下载 egg egg-bin egg-mysql包
- 在app下面创建router.js文件
- 在app下创建controller控制器文件夹
- 在app下创建services 服务文件夹
- 创建config 配置文件夹
- 在config下创建config.default.就是 配置项目
- 在config下创建plugin.js文件
参数
- post—->this.ctx.request.body
- get —->this.ctx.request.query
- 动态id->this.ctx.params
egg+mysql+redis
直接用脚手架
$ mkdir egg-example && cd egg-example
$ npm init egg —type=simple
$ npm i
下载mysql和redis依赖包
npm i egg-mysql egg-redis —save
没有mysql和redis需先下载
配置config
config/plugin.js添加上:
redis: {enable: true,package: 'egg-redis',},mysql: {enable: true,package: 'egg-mysql',},
config/config.default.js 添加以下:
config.redis = {client: {port: 6379,host: '127.0.0.1',password: '',db: 0,},};config.mysql = {client: {host: 'localhost',port: '3306',user: 'root',password: '12344321',database: 'exam',},app: true,agent: false,};
在请求数据的时候,先去redis找缓存数据,没有再去数据库拿数据,并且将拿到的数据进行缓存;
- app/controller/home.js ```javascript ‘use strict’;
const Controller = require(‘egg’).Controller;
class HomeController extends Controller { async index() { console.time(‘index-time’); const { ctx } = this; let userList = await ctx.service.home.get(‘userList’);//取缓存数据 if (!userList) { userList = await ctx.service.home.userList(); await ctx.service.home.set(‘userList’, userList);//存缓存数据 } ctx.body = userList; console.timeEnd(‘index-time’); } }
module.exports = HomeController;
- app/service/home.js```javascript'use strict';const Service = require('egg').Service;class HomeService extends Service {async set(key, value, seconds) {//存数据value = JSON.stringify(value);if (this.app.redis) {if (!seconds) {await this.app.redis.set(key, value);} else {await this.app.redis.set(key, value, 'EX', seconds);}}}async get(key) {//取数据if (this.app.redis) {const data = await this.app.redis.get(key);if (!data) return;return JSON.parse(data);}}async userList() {const sql = 'select * from user';return this.app.mysql.query(sql);}}module.exports = HomeService;
