nodejs 服务器实现负载均衡

server.js

javascript 复制代码
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const axios = require('axios');

const app = express();

// 定义后端服务列表
const services = [
    { target: 'http://localhost:3001' },
    { target: 'http://localhost:3002' }
];

// 检查服务存活性
async function isServiceAlive(target) {
    try {
        const response = await axios.get(target, { timeout: 2000 });
        return response.status === 200;
    } catch (error) {
        console.error(`Service at ${target} is not alive:`, error.message);
        return false;
    }
}

// 获取活跃的服务
async function getActiveServices() {
    const checkPromises = services.map(async (service) => {
        const isAlive = await isServiceAlive(service.target);
        return isAlive ? service : null;
    });
    const results = await Promise.all(checkPromises);
    return results.filter(service => service);
}

// 使用负载均衡中间件
app.use(async (req, res, next) => {
    const activeServices = await getActiveServices();

    if (activeServices.length > 0) {
        const randomService = activeServices[Math.floor(Math.random() * activeServices.length)];
        createProxyMiddleware({
            target: randomService.target,
            changeOrigin: true,
            onError: (err, req, res) => {
                console.error(`Proxy error: ${err.message}`);
                res.status(502).send('Bad Gateway');
            }
        })(req, res, next);
    } else {
        res.status(503).send('No available services');
    }
});

// 启动负载均衡服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Load balancer is running on http://localhost:${PORT}`);
});

server1.js

javascript 复制代码
const express = require('express');
const app = express();
const path = require("path")
app.use(express.static(path.join(__dirname, 'public')));


const PORT = 3001;
app.listen(PORT, () => {
    console.log(`Server 1 is running on http://localhost:${PORT}`);
});

server2.js

javascript 复制代码
const express = require('express');
const app = express();
const path = require("path")
app.use(express.static(path.join(__dirname, 'public')));


const PORT = 3002;
app.listen(PORT, () => {
    console.log(`Server 2 is running on http://localhost:${PORT}`);
});
相关推荐
Robpubking2 小时前
AWS 中 S3 的 server-side encryption 解释与说明
运维·aws
喝养乐多长不高4 小时前
SpringCloud:Eureka和负载均衡
spring cloud·eureka·服务发现·负载均衡·cap·服务注册
陌路205 小时前
Linux 34TCP服务器多进程并发
linux·服务器·网络
爱喝矿泉水的猛男5 小时前
单周期Risc-V指令拆分与datapath绘制
运维·服务器·risc-v
科技块儿5 小时前
【IP】公有&私有IP地址?
服务器·网络协议·tcp/ip
hakukun5 小时前
docker避免每次sudo方法
运维·docker·容器
杨凯凡5 小时前
Docker Compose:多容器应用编排入门与实战
运维·docker·容器
jason.zeng@15022075 小时前
my.cnf详解
运维·数据库·adb
灵神翁5 小时前
自建node云函数服务器
运维·服务器
TangDuoduo00056 小时前
【IO模型与并发服务器】
运维·服务器·网络·tcp/ip