由於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服務重要性不言而喻因此特別作一個專題來討論