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}`);
});
相关推荐
春日见25 分钟前
Tool文件夹:瑞士军刀库
运维·服务器·windows·深度学习·自动驾驶
AC赳赳老秦30 分钟前
Windows 系统 OpenClaw 执行策略报错及管理员权限设置深度解析与实操指南
运维·人工智能·python·django·自动化·媒体·openclaw
Gofarlic_OMS38 分钟前
SolidEdge专业许可证管理工具选型关键评估标准
java·大数据·运维·服务器·人工智能
萝卜白菜。1 小时前
TongWeb7.0 集中管理heimdall配置文件说明
linux·运维·服务器
bingHHB1 小时前
金蝶云星空旗舰版 × 赛狐ERP:亚马逊卖家业财一体化的最后一公里
运维·数据库·集成学习
ji_shuke2 小时前
CloudFront 跨域问题(CORS)的几种解决方式
服务器·cloudfront
IMPYLH2 小时前
Linux 的 install 命令
linux·运维·服务器·bash
寻道模式2 小时前
【运维心得】“龙虾”非本地访问的坑
运维·服务器
浦信仿真大讲堂3 小时前
CST FAQ 006:Linux系统CST安装指导
linux·运维·服务器·仿真软件·达索软件
脑子加油站3 小时前
Ansible自动化工具
运维