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}`);
});
相关推荐
IMPYLH6 小时前
Linux 的 pinky 命令
linux·运维·服务器·bash
HelloWorld_SDK6 小时前
Docker安装OpenClaw
运维·docker·容器·openclaw
REDcker6 小时前
Linux iptables 与 Netfilter:原理、路径与运维要点
linux·运维·服务器
KKKlucifer8 小时前
零信任融合实践:国内堡垒机如何落地动态权限与实时阻断
运维
Bert.Cai9 小时前
Linux useradd命令详解
linux·运维
无忧.芙桃10 小时前
进程控制(上)
linux·运维·服务器
Bert.Cai10 小时前
Linux rm命令详解
linux·运维
航Hang*10 小时前
Windows Server 配置与管理——第8章:配置Web服务器
运维·服务器·windows·学习·vmware
hweiyu0011 小时前
Linux命令:suspend
linux·运维·服务器
code_li11 小时前
服务器与普通PC区别?
运维·服务器