(2) egg - 기초 기능

27221 단어 nodejs
(1) egg - 기초 기능
  • 1. 정시 임무
  • (2) 프레임 확장
  • (1)Application
  • (2)Context
  • (3)request & response
  • (3) 시동
  • 1. 정시 임무
  • (1) 정시 작업 을 작성 하 는 모든 정시 작업 은 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 에 마 운 트 합 니 다.
  • (2) 정시 방식 의 정시 임 무 는 interval 또는 cron 두 가지 서로 다른 정시 방식 을 지정 할 수 있다.interval: 숫자 나 문자 형식 cron 으로 설정 할 수 있 습 니 다. 정시 작업 의 실행 시 기 를 설정 하고 cron 표현 식 은 cron - parser 를 통 해 해석 할 수 있 습 니 다.
  • module.exports = {
      schedule: {
        //           
        cron: '0 0 */3 * * *',
      },
    };
    
  • (3) 정시 작업 유형 은 기본적으로 두 가지 유형 을 지원 합 니 다. 워 커 와 all 워 커 유형: 모든 기계 에 하나의 워 커 만 이 정시 작업 을 수행 합 니 다 all 유형: 기계 에 있 는 모든 워 커 는 이 정시 작업 을 수행 합 니 다.
  • (4) 기타 매개 변수
  • cronOption: cron 의 시간 대 immediate 설정: 정시 작업 을 시작 한 후 바로 정시 작업 을 수행 할 지 여 부 를 설정 합 니 다 disable: true 로 설정 할 때 이 정시 작업 은 env: 배열 형식 을 시작 하지 않 고 지정 한 환경 에서 만 시 작 됩 니 다.
  • (5) 다른 것 은 app. runSchedule (schedulePath) 을 통 해 정시 작업 을 실행 할 수 있 습 니 다. 해당 하 는 정시 작업 을 수행 하고 promise 를 되 돌려 줍 니 다.

  • 확장 정시 작업: 프레임 워 크 의 기본 정시 작업 은 모든 기계 의 단일 프로 세 스 실행 과 모든 프로 세 스 실행 만 지원 합 니 다. 어떤 경우 에는 하나의 클 러 스 터 의 특정한 프로 세 스 가 정시 작업 을 수행 하 는 수요 가 있 을 수 있 습 니 다.상부 프레임 워 크 에서 새로운 정시 작업 유형 을 확장 할 수 있 습 니 다. 에이전트. 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 클래스 로 되 돌아 갑 니 다. 일부 라 이 프 사이클 방법 을 정의 하여 응용 과정 에서 초기 화 작업 을 시작 할 수 있 습 니 다.
  • 프로필 이 불 러 올 것 입 니 다. 마지막 으로 설정 을 동적 으로 수정 할 시기 입 니 다 (configWillLoad)
  • 프로필 로드 완료 (configDidLoad)
  • 파일 로드 완료 (didLoad)
  • 플러그 인 시작 완료 (willReady)
  • worker 준비 완료 (didReady)
  • 응용 프로그램 시작 완료 (server DidReady)
  • 응용 프로그램 이 곧 종 료 됩 니 다 (beforeClose)
  • // 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;
    

    좋은 웹페이지 즐겨찾기