express实现node多进程微服务

const http = require('http');
const express = require('express');
const mysql = require('mysql');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const app = express();

// 多进程
if (cluster.isMaster) {
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }
    cluster.on('exit', () => {
        console.log(`工作进程 ${process.pid} 已退出`);
    });
} else {
    const server = app.use(express.static(__dirname)).listen(3000, 'localhost', () => {
        const host = server.address().address;
        const port = server.address().port;
        console.log("工作进程 %s 运行在 http://%s:%s", process.pid, host, port);
    });
}

// 路由
app.get('/', (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
    res.end('<a href="/home">home</a><br/><a href="/about">about</a>');
});

app.get('/home', (req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
    res.end('<div>'+cluster.worker.id+'</div><div>'+process.pid+'</div>');
});

app.get('/about', (req, res) => {
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : '123456',
        port: '3306',
        database: 'download'
    });
    var sql = 'SELECT * FROM imooc';
    connection.query(sql, (err, result) => {
        if(err){
            console.log('[SELECT ERROR] - ',err.message);
            return;
        }
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
        res.end(JSON.stringify(result));
    });
});

 

posted @ 2017-12-15 17:41  鱿鱼须须  阅读(1157)  评论(0编辑  收藏  举报