상단

Service


 

Worker ID 지정


PM2를 사용하여 고정된 worker ID를 지정 한다.

 
//--- vi  ecosystem.config.js
mudule.exports = {
  apps: [
      {
          wait_ready: true,
          listen_timeout: 3000,
          kill_timeout: 5000,
          instance_var: 'INSTANCE_ID'
          
      }
  ]  
};

//--- vi  include/Application.js
//---     appl.id : 1, 2, 3, ...
import cluster from 'cluster';

global.appl = {
    isPM2: (process.env.PM2 == 'true'),
    id: -1
};

if (appl.isPM2) {
    appl.id = parseInt(process.env.INSTANCE_ID) + 1;
    appl.type = 'pm2';
    appl.seq = parseInt(process.env.INSTANCE_ID) + 1;
}

if (cluster.isMaster) {
    cluster.on('message', function(worker, message) {
        if (message.type == 'work:init') {
            global.appl.worker.id = message.worker.id;
        }
        
    }.bind(this));
    
    const countWorker = 3;
    for (let idx = 0; idx < countWorker; idx++) {
        const worker = cluster.fork();
        
        setTimeout(() => {
            worker.send({
                type: 'work:init',
                'worker': {
                    id: idx + 1
                }
            });
        }, 500);
    }
} else {
    await utils.wait(() => (appl.worker.id != -1), 2 * 1000);
}
 

Service 정상 종료


const workType = () => {
    if (appl.isPM2) {
        return `PM2 worker ${appl.worker.id}`;
    } else {
        return (cluster.isMaster) ? 'Master':`Worker ${cluster.worker.id}`;
    }
}

const gracefulShutdown = (exitName = 'None', signal = '') => {
    logger.error(`GracefulShutdown in ${workType()}, exit - ${exitName}`);
    
    process.exit(1);
}

if (appl.isPM2) {
    process.on('SIGINT', function () {
        gracefulShutdown('SIGINT');
    }.bind(this));
} else {
    process.on('SIGINT', function () {
        gracefulShutdown('SIGINT');
    }.bind(this));
            
    process.on('SIGTERM', function (signal) {
        gracefulShutdown('SIGTERM', signal);
    }.bind(this));
            
    process.on('exit', function() {
        console.log('exit ----');
    }.bind(this));
}
 

IPC


Inter Process Community

 

Cache


 

 

최종 수정일: 2024-09-30 12:26:20

이전글 :
다음글 :