nodeJS 는 여러 개의 키 프로 세 스 를 동시에 실행 합 니 다.

4193 단어 백 엔 드
게임 프로젝트 개발 에 있어 로비 에 여러 개의 서브루틴 이 들 어 있 는 모델 을 자주 만 날 수 있 습 니 다. 이 럴 때 nodeJs 를 서버 로 사용 할 때 여러 개의 프로 세 스 에 대한 관리 와 구조 문제 와 관련 되 고 예전 의 실제 개발 경험 과 결합 하여 이런 모델 의 서버 디자인 에 대해 간단 한 정 리 를 할 수 있 습 니 다.
1.  핵심 모듈
child_process 와 fs
child_프로 세 스 모듈 은 주 프로 세 스 가 실 행 될 때 주 프로 세 스에 독립 된 비동기 서브 프로 세 스 를 파생 시 키 는 데 사 용 됩 니 다.
fs 모듈 은 주 프로 세 스 에서 필요 한 프로필 을 읽 는 데 사 용 됩 니 다.
2.  실현 방식
우선 하위 프로 세 스 의 정 보 를 설정 할 프로필 이 필요 합 니 다. 보통 json 파일 을 사용 합 니 다. 예 를 들 어:
[
{
“name”:”game1”,
“path”:”Game/game1”,
“port”:1100,
“status”:0,
"des": "하위 프로 세 스 1"
},
{
“name”:”game2”,
“path”:”Game/game2”,
“port”:1200,
“status”:0,
"des": "하위 프로 세 스 2"
},
{
“name”:”game3”,
“path”:”Game/game3”,
“port”:1300,
“status”:0,
"des": "하위 프로 세 스 3"
}
]
이러한 json 파일 은 실행 해 야 할 하위 프로 세 스 의 이름, 실행 중인 js 파일 의 경로, 포트, 서버 의 상 태 를 정의 하고 이 정 보 를 설명 합 니 다.
다음 함수 예제 는 실행 중인 메 인 프로 세 스 에서 이러한 방법 으로 설정 파일 정 보 를 가 져 올 수 있 습 니 다.
/**
 *       
 * @param {string}manifestUrl   json  
 * @returns {Promise>}
 */
private async getManifest(manifestUrl:string):Promise> {
        let manifest = [];
        let fileName = await path.resolve(__dirname,manifestUrl);
        let exists = await fs.existsSync(fileName);
        if (exists) {
            let manifestStr = awaitfs.readFileSync(fileName);
            if (manifestStr) {
                try {
                     manifest = await JSON.parse(manifestStr.toString("utf-8"));
                } catch (e) {
                    console.error(config.manifestFileName+ "  !", e.message);
                }
            }
        } else {
            console.error(config.manifestFileName+ "   !");
            process.exit(0);
        }
    return manifest;
}

다음 함수 예제 에서 하나의 프로 세 스 를 실행 할 수 있 습 니 다. 하나의 item 은 설정 대상 의 노드 요소 입 니 다.
/**
 *       
 * @param item
 * @param restart
 */
private async runInstance(item: any, restart = 0) {
    let instanceObj = {
        name: item.name,
        desc: item.desc,
        path: item.path,
        port: item.port,
        status: item.status,
        cpu: "0%",
        memory: "0%",
        restart: restart,
        instance: null,
        version: "0"
    };
    if (!instanceObj["timer"]){
        instanceObj["timer"] = setTimeout(()=> {
            if (instanceObj.status== 0) {
                instanceObj.restart = 0;
                instanceObj["timer"]= null;
                delete instanceObj["timer"];
            }
        }, 500);
    }
    if (item.status != 1) {
        let arg = {
            port: item.port,
            serverName: item.name,
        };
        //     
        let logPath = "";
        let pathArr = item.path.split("/");
        for (let i = 0; i< pathArr.length - 1; i++) logPath += pathArr[i] + "/";
        instanceObj["logPath"]= logPath + "Logs.txt";
        // fork    
        instanceObj.instance = cps.fork(path.resolve(__dirname,"./controller/" + item.path), [encodeURIComponent(JSON.stringify(arg))],{silent: true});
        //       
        instanceObj.instance.stdout.on("data",async (data: Buffer) => {
            // todo      log.txt
        });
        //     
        instanceObj.instance.stderr.on("data",async (data: Buffer) => {
            // todo            
        });
        //     
        instanceObj.instance.on("message",async (msg: any) => {
            if (msg &&msg.method && this[msg.method]) {
                instanceObj &&instanceObj.instance && instanceObj.instance.send({
                    method: msg.method,
                    data: await this[msg.method](...msg.arg)
                })
            }
        });
    }
}

이 모드 는 모든 프로 세 스 의 메모리, cpu 버 전 정 보 를 관리 하 는 데 편리 합 니 다. 모든 하위 프로 세 스 는 하나의 클래스 를 계승 하여 process. argv [2] 를 통 해 포트, 버 전 등 정 보 를 관리 할 수 있 습 니 다.
 

좋은 웹페이지 즐겨찾기