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}`);
});
相关推荐
比奥利奥还傲.30 分钟前
Linux运维安全新范式:基于TCPIP与SSH密钥的无密码认证实战
linux·运维·安全
moppol1 小时前
探索下一代云存储技术:对象存储、文件存储与块存储的区别与选择
服务器
mmsx1 小时前
使用git生成ssh的ed25519密钥
运维·git·ssh
ZeroNews内网穿透2 小时前
服装零售企业跨区域运营难题破解方案
java·大数据·运维·服务器·数据库·tcp/ip·零售
果子⌂2 小时前
容器技术入门之Docker环境部署
linux·运维·docker
神的孩子都在歌唱2 小时前
常见的网络攻击方式及防御措施
运维·服务器·网络
深度学习04073 小时前
【Linux服务器】-安装ftp与sftp服务
linux·运维·服务器
阿巴~阿巴~5 小时前
Linux 第一个系统程序 - 进度条
linux·服务器·bash
小白爱电脑5 小时前
什么是2.5G交换机?
运维·网络·5g·千兆宽带
?ccc?5 小时前
容器技术技术入门与 Docker 环境部署
运维·docker·容器