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}`);
});
相关推荐
Loongproxy9 分钟前
抖音企业号更换公司主体怎么操作?矩阵账号配静态长效IP的稳定方案
服务器·网络·网络协议·tcp/ip
小周学学学1 小时前
RustDesk 项目解读:适合桌面运维的开源自托管远程桌面方案
运维·ad域
智恒百亿7 小时前
RTX 5090 全场景技术应用解析:从游戏算力到专业生产力落地
大数据·服务器·游戏
OpenCloudOS8 小时前
从快速响应到问题发现:一次backport挖出全新漏洞CVE-2026-76641
服务器·网络·安全
张文君8 小时前
ubuntu26.04从ext4改成mdadm的raid1+lvm启动
linux·运维·网络
DevHub9 小时前
QEMU + Busybox 搭建嵌入式 Linux 开发环境:内核编译到启动,30 秒一个迭代
linux·运维·服务器
ouynagda9 小时前
Linux 进程管理详解:从概念到实践
linux·运维·网络
2401_890603409 小时前
Linux 基础文件IO
linux·运维·服务器
tx11208763589 小时前
K8S-pod管理与控制器管理
linux·运维·kubernetes·pod