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添加上:

    1. redis: {
    2. enable: true,
    3. package: 'egg-redis',
    4. },
    5. mysql: {
    6. enable: true,
    7. package: 'egg-mysql',
    8. },
  • config/config.default.js 添加以下:

    1. config.redis = {
    2. client: {
    3. port: 6379,
    4. host: '127.0.0.1',
    5. password: '',
    6. db: 0,
    7. },
    8. };
    9. config.mysql = {
    10. client: {
    11. host: 'localhost',
    12. port: '3306',
    13. user: 'root',
    14. password: '12344321',
    15. database: 'exam',
    16. },
    17. app: true,
    18. agent: false,
    19. };

在请求数据的时候,先去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;

  1. - app/service/home.js
  2. ```javascript
  3. 'use strict';
  4. const Service = require('egg').Service;
  5. class HomeService extends Service {
  6. async set(key, value, seconds) {//存数据
  7. value = JSON.stringify(value);
  8. if (this.app.redis) {
  9. if (!seconds) {
  10. await this.app.redis.set(key, value);
  11. } else {
  12. await this.app.redis.set(key, value, 'EX', seconds);
  13. }
  14. }
  15. }
  16. async get(key) {//取数据
  17. if (this.app.redis) {
  18. const data = await this.app.redis.get(key);
  19. if (!data) return;
  20. return JSON.parse(data);
  21. }
  22. }
  23. async userList() {
  24. const sql = 'select * from user';
  25. return this.app.mysql.query(sql);
  26. }
  27. }
  28. module.exports = HomeService;