queue 큐 활용

최원상·2023년 7월 3일
0

GCP pub/sub에서 데이터를 받아 DB에 넣는 작업 중
nodejs pub/sub의 통신이 비동기로 처리되어 데이터 텀이 짧을 경우 데이터가 꼬이는 현상이 있어 큐를 활용하여 동기화 처리 진행
처리할 콜백 함수를 받고 데이터가 들어 올때마다 잠김상태를 확인하여 1개의 루프만 돌아가도록 설계

'use strict'
class Mqueue {

    constructor() {

        this.queue = Array();
        this.lock = false;
        this.fn;

    }

    async send(obj) {
        this.queue.push(obj);

  
        if(!this.lock){
       
            this.lock = true;
     

            while(this.queue.length >0){
                await this.fn(this.queue.shift());
            }
            this.lock = false;
     
        }
    }

    setFn(fn){
        this.fn = fn;
    }


   

}

module.exports = Mqueue
profile
한 줄로는 안되지

0개의 댓글