nodeJS 는 여러 개의 키 프로 세 스 를 동시에 실행 합 니 다.
4193 단어 백 엔 드
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] 를 통 해 포트, 버 전 등 정 보 를 관리 할 수 있 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
심도 분석: 자바 에서 어떻게 이상 한 지 한 편 으로 해결 해 드릴 게 요!1. try 코드 블록 에 이상 이 발생 할 수 있 는 코드 를 넣 었 습 니 다. try 에 이상 이 생기 면 try 코드 블록 에 있 는 프로그램 은 계속 실행 되 지 않 고 catch 에 있 는 코드 에 맡 겨...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.