由于egg知识点丰富,分为上下两章点击见上章javascript
Node.js 性能平台(alinode)java
是面向全部 Node.js 应用提供 性能监控、安全提醒、故障排查、性能优化
等服务的总体性解决方案,提供完善的工具链和服务,协助开发者快速发现和定位线上问题。node
npm i nodeinstall -g
复制代码
提供了egg-alinode 来快速接入,无需安装 agenthub
等额外的常驻服务。git
npm i egg-alinode --save
复制代码
// /config/plugin.js
exports.alinode = {
enable:true,
package:'egg-alinode',
},
复制代码
控制台地址:node.console.aliyun.comredis
// config/config.default.js
exports.alinode = {
enable: true,
appid: '***', // Node.js 性能平台给您的项目生成的 appid
secret: '***', // Node.js 性能平台给您的项目生成的 secret
logdir: '***', //可选,Node.js 性能平台日志输出地址绝对路径,与 NODE_LOG_DIR 保持一致。如:/tmp/,也能够不写
error_log: [
// '您的应用在业务层面产生的异常日志的路径,数组,可选,可配置多个',
// '例如:/root/.logs/error.#YYYY#-#MM#-#DD#.log',
// '不更改 Egg 默认日志输出路径可不配置本项目',
],// 可选
agentidMode:'IP', // 可选,若是设置,则在实例ID中添加部分IP信息,用于多个实例 hostname 相同的场景(以容器为主)
};
复制代码
而后你就能愉快针对你的egg,进行监控了mongodb
获取swgger地址 输入浏览器apache
你看到就是文档了npm
点击try it out
输入你传的值,而后点击Execute
结果
你就能够获取到接口传递过来的值,效果相似postman,可是清晰程度比postman好
通常状况下都不会有问题,可是若是你这时候巧妙的用了egg-static,那么你就会报错了
通过排查,你就会发现
/node_modules/egg-swagger2/app.js
它会是一个数组,而后报错必须是个字符串,而后你懂得..你给他作成一个字符串便可
exports.ejs = {
enable: true,
package: 'egg-view-ejs',
};
复制代码
a:静态文件
config.static = {
prefix: '/',
dir: path.join(appInfo.baseDir, 'app/public/')
}
复制代码
固然此时你会遇到一个问题,你想要多个文件该如何事好
config.static = {
prefix: '/',
dir: [ path.join(appInfo.baseDir, 'app/view/'),
path.join(appInfo.baseDir, 'app/public/uploads/'),
path.join(appInfo.baseDir, 'app/public/swagger/') ],
};
复制代码
b:模板设置
config.view = {
defaultExt: '.html',
mapping: {
'.ejs': 'ejs',
'.html': 'ejs',
}
}
复制代码
//将 index.html 放在app/view里,静态文件放在public里
const { ctx } = this;
// render user.html
yield ctx.render('index');
复制代码
做为后台,例若有人须要后台提供文档....人家java都有swagger,egg在 egg-swagger2 支持下,咱们也可使用。
npm i egg-swagger2 -S
// config/plugin.js
exports.swagger2 = {
enable: true,
package: 'egg-swagger2',
};
复制代码
config.default.js 中配置
config.swagger2 = {
enable: true, // 禁用swagger , 默认为true
base: {
/* default config,support cover
schemes: [
'http',
],
host: '127.0.0.1:7001',
basePath: '/',
consumes: [
'application/json',
],
produces: [
'application/json',
],
*/
info: {
description: '文档介绍,
version: '1.0.0',
title: '文档名称',
contact: {
email: 'caandoll@aliyun.com',
},
license: {
name: 'Apache 2.0',
url: 'http://www.apache.org/licenses/LICENSE-2.0.html',
},
},
tags: [{
name: 'admin',
description: 'Admin desc',
},
{
name: 'role',
description: 'Role desc',
},
],
definitions: {
// model definitions
},
securityDefinitions: {
// security definitions
}
},
};
复制代码
module.exports = app => {
const { router, controller, swagger } = app;
router.post('/login', controller.test.postLogin);
swagger.post('/login', {
tags: [
'admin',
],
summary: 'Login a admin',
description: '',
parameters: [
{
in: 'body',
name: 'body',
description: 'admin\'s username & password',
required: true,
schema: {
type: 'object',
required: [ 'username', 'password' ],
properties: {
username: {
type: 'string',
description: 'admin\'s username',
},
password: {
type: 'string',
description: 'admin\'s password',
},
},
},
},
],
responses: {
200: {
description: 'SUCCEED',
schema: {
type: 'object',
properties: {
status: {
type: 'string',
description: 'status',
},
data: {
type: 'object',
description: 'data',
properties: {
token: {
type: 'string',
description: 'token',
},
},
},
},
},
},
},
});
}
复制代码
module.exports = app => {
const { router, controller, swagger } = app;
router.get('/roles', controller.test.getRoles);
swagger.get('/roles', {
tags: ['role',],
summary: 'search role by page',
description: '',
parameters: [{
in: 'query',
name: 'name',
description: 'role\'s name',
},
{
in: 'query',
name: 'pageIndex',
description: 'pageIndex',
},
{
in: 'query',
name: 'pageSize',
description: 'pageSize',
},
],
responses: {
200: {
description: 'SUCCEED',
schema: {
type: 'object',
properties: {
status: {
type: 'string',
description: 'status',
},
datas: {
type: 'array',
description: 'result datas',
properties: {
token: {
type: 'string',
description: 'token',
},
},
},
pageIndex: {
type: 'number',
description: 'pageIndex',
},
pageSize: {
type: 'number',
description: 'pageSize',
},
totalCount: {
type: 'number',
description: 'totalCount',
},
},
},
},
},
});
}
复制代码
npm run dev 跑起来
获取swgger地址 输入浏览器
你看到就是文档了
点击try it out
输入你传的值,而后点击Execute
结果
你就能够获取到接口传递过来的值,效果相似postman,可是清晰程度比postman好
通常状况下都不会有问题,可是若是你这时候巧妙的用了egg-static,那么你就会报错了
通过排查,你就会发现
/node_modules/egg-swagger2/app.js
它会是一个数组,而后报错必须是个字符串,而后你懂得..你给他作成一个字符串便可
npm egg-validate-plus --save
// config/plugin.{env}.js
exports.validatePlus = {
enable: true,
package: 'egg-validate-plus',
};
复制代码
// config/config.{env}.js
config.validatePlus = {
resolveError(ctx, errors) {
if (errors.length) {
ctx.type = 'json';
ctx.status = 400;
ctx.body = {
code: 400,
error: errors,
message: '参数错误',
};
}
}
};
复制代码
// app/controller/xx.js
const { query } = this.ctx.request;
复制代码
拿到验证结果
const validateResult = await this.ctx.validate('user.login', query)
复制代码
验证不经过时,阻止后面的代码执行
if (!validateResult) return
复制代码
// app/controller/xx.js
// 直接引入 rules 文件下的验证规则,也能够是本身写的验证规则对象
const rule = this.app.rules.user.login
// 数据格式
// const rule = {
// id: [
// { required: true },
// { type: 'number', message: 'id 必须为数字 }
// ],
// password: [
// { required: true },
// { type: 'string', message: 'password 必须为字符串 }
// ]
// }
// 从客户端传入的参数
const { query } = this.ctx.request;
// 数据格式:
// query = {
// username: 123456,
// password: 'abcdefg'
// }
// 拿到验证结果
const validateResult = await this.ctx.validate(rule, query)
// 验证不经过时,阻止后面的代码执行
if (!validateResult) return
复制代码
Redis client(support redis portocal) based on ioredis for egg framework
npm i egg-redis --save
复制代码
Change ${app_root}/config/plugin.js
to enable redis plugin:
exports.redis = {
enable: true,
package: 'egg-redis',
};
复制代码
Configure redis information in ${app_root}/config/config.default.js
:
Single Client
config.redis = {
client: {
port: 6379, // Redis port
host: '127.0.0.1', // Redis host
password: 'auth',
db: 0,
}
}
复制代码
app/service/redis.js if(this.app.redis)
判断是否有启用redis
'use strict';
const Service = require('egg').Service;
class RedisService 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);
}
}
}
module.exports = RedisService;
复制代码
app/controller/default/index.js若是没有设置redis缓存,就去请求数据,再设置缓存
var topNav = await this.ctx.service.cache.get('index_topNav');
if (!topNav) {
topNav = await this.ctx.model.Nav.find({
"position": 1
});
await this.ctx.service.cache.set('index_topNav', topNav, 60 * 60);
}
复制代码
mongodb 对于node服务重要性不言而喻因此特别作一个专题来讨论