(2) egg - 기초 기능
27221 단어 nodejs
app/shedule
디 렉 터 리 에 놓 여 있 습 니 다. 모든 파일 은 독립 된 정시 작업 입 니 다. 정시 작업 과 실행 할 방법 을 설정 할 수 있 습 니 다.예 를 들 어 원 격 데 이 터 를 메모리 캐 시 에 업데이트 하 는 정시 작업 은 app/schedule
디 렉 터 리 아래 에 파일 을 만 들 수 있 습 니 다. const Subscription = require('egg').Subscription;
class UpdateCache extends Subscription {
// schedule
static get schedule() {
return {
interval: '1m', // 1
type: 'all', // worker
};
}
// subscribe
async subscribe() {
const res = await this.ctx.curl('http://www.api.com/cache', {
dataType: 'json',
});
this.ctx.app.cache = res.data;
}
}
module.exports = UpdateCache;
//
module.exports = {
schedule: {
interval: '1m', // 1
type: 'all', // worker
},
//ctx service
async task(ctx) {
const res = await ctx.curl('http://www.api.com/cache', {
dataType: 'json',
});
ctx.app.cache = res.data;
},
};
상기 정시 작업 은 워 커 프로 세 스 마다 1 분 에 한 번 씩 실 행 됩 니 다. 원 격 데 이 터 를 app. cache 에 마 운 트 합 니 다.
module.exports = {
schedule: {
//
cron: '0 0 */3 * * *',
},
};
확장 정시 작업: 프레임 워 크 의 기본 정시 작업 은 모든 기계 의 단일 프로 세 스 실행 과 모든 프로 세 스 실행 만 지원 합 니 다. 어떤 경우 에는 하나의 클 러 스 터 의 특정한 프로 세 스 가 정시 작업 을 수행 하 는 수요 가 있 을 수 있 습 니 다.상부 프레임 워 크 에서 새로운 정시 작업 유형 을 확장 할 수 있 습 니 다. 에이전트. js 에서 에이전트. ScheduleStrategy 를 계승 하고 에이전트. schedule. use () 를 통 해 등록 하면 됩 니 다.
module.exports = agent => {
class ClusterStrategy extends agent.ScheduleStrategy {
start() {
// ,
// schedule (scene)
// this.sendOne() worker task
//this.sendAll() worker task
agent.mq.subscribe(schedule.scene, () => this.sendOne());
}
}
agent.schedule.use('cluster', ClusterStrategy);
};
(2) 프레임 확장
(1)Application
app 대상 은 전역 응용 대상 으로 응용 프로그램 이 시 작 될 때 생 성 됩 니 다.controller, Middlewaere, helper, Service 에서 this. app 를 통 해 application 대상 에 접근 할 수 있 습 니 다.
확장 방식: 프레임 워 크 는 app / extend / application. js 에서 정의 하 는 대상 을 application 의 prototype 대상 과 통합 시 킵 니 다. 시작 하면 합 친 app 대상 을 생 성 합 니 다.1. 방법 확장
// app/extend/application.js
module.exports = {
foo(param) {
// this app , app ,
},
};
2. 속성 확장 속성 에 대한 계산 은 한 번 만 하기 때문에 캐 시 를 해 야 합 니 다.
// app/extend/application.js
const BAR = Symbol('Application#bar');
module.exports = {
get bar() {
// this app , app ,
if (!this[BAR]) {
//
this[BAR] = this.config.xx + this.config.yy;
}
return this[BAR];
},
};
(2)Context
context 는 요청 단계 의 대상 입 니 다. 요청 할 때마다 ctx 인 스 턴 스 를 생 성 합 니 다.미들웨어 에서: this 는 ctx contrller 에서: 클래스 의 쓰기 방법 은 this. ctx 입 니 다. 방법 은 ctx helper service 에서: this 는 helper, service 대상 자 체 를 가리 키 고 this. ctx 를 통 해 contex 대상 을 방문 합 니 다.
확장 방식: 프레임 워 크 는
app/extend/context.js
에서 정 의 된 대상 과 context 의 prototype 대상 을 합 쳐 요청 을 처리 할 때 확 장 된 prototype 을 기반 으로 ctx 대상 을 생 성 합 니 다.(1) 확장 방법// app/extend/context.js
module.exports = {
foo(param) {
// this ctx , ctx ,
},
};
(2) 속성 확장
// app/extend/context.js
const BAR = Symbol('Context#bar');
module.exports = {
get bar() {
// this ctx , ctx ,
if (!this[BAR]) {
// , header ,
this[BAR] = this.get('x-bar');
}
return this[BAR];
},
};
(3)request & response
1. request request 접근 방식: ctx 와 ctx. request 접근 속성 과 방법 을 사용 하 는 것 은 등가 입 니 다.
ctx.url === ctx.request.url
확장 방법:
// app/extend/request.js
module.exports = {
get foo() {
return this.get('x-request-foo');
},
};
2. response 는 ctx 와 ctx. response 를 사용 하여 방문 하 는 것 이 등가 입 니 다.확장 모드:
// app/extend/response.js
module.exports = {
set foo(value) {
this.set('x-response-foo', value);
},
};
(3) 시작
프레임 워 크 는 통 일 된 입구 파일 (app. js) 을 제공 하여 시작 과정 을 사용자 정의 합 니 다. 파일 은 boot 클래스 로 되 돌아 갑 니 다. 일부 라 이 프 사이클 방법 을 정의 하여 응용 과정 에서 초기 화 작업 을 시작 할 수 있 습 니 다.
// app.js
class AppBootHook {
constructor(app) {
this.app = app;
}
configWillLoad() {
// config ,
//
// :
// : ,
this.app.config.mysql.password = decrypt(this.app.config.mysql.password);
// : coreMiddleware
const statusIdx = this.app.config.coreMiddleware.indexOf('status');
this.app.config.coreMiddleware.splice(statusIdx + 1, 0, 'limit');
}
async didLoad() {
//
// ,
// :
this.app.queue = new Queue(this.app.config.queue);
await this.app.queue.init();
// :
this.app.loader.loadToContext(path.join(__dirname, 'app/tasks'), 'tasks', {
fieldClass: 'tasksClasses',
});
}
async willReady() {
// , ready
// ,
// :
this.app.cacheData = await this.app.model.query(QUERY_CACHE_SQL);
}
async didReady() {
//
const ctx = await this.app.createAnonymousContext();
await ctx.service.Biz.request();
}
async serverDidReady() {
// http / https server ,
// app.server server
this.app.server.on('timeout', socket => {
// handle socket timeout
});
}
}
module.exports = AppBootHook;
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Node.js를 AWS서버에서 사용하는 실습간단한 예제와 함께 AWS에서 Node.js를사용하는 법을 배워보도록 하겠다. 해당 github에 있는 레포지토리로 사용을 할 것이다. 3000번 포트로 Listen되는 예제이고 간단히 GET, POST, DELET...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.