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}`);
});
相关推荐
勤奋的凯尔森同学20 分钟前
webmin配置终端显示样式,模仿UbuntuDesktop终端
linux·运维·服务器·ubuntu·webmin
丁卯4041 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
chengooooooo1 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
人间打气筒(Ada)3 小时前
MySQL主从架构
服务器·数据库·mysql
落笔画忧愁e4 小时前
FastGPT快速将消息发送至飞书
服务器·数据库·飞书
小冷爱学习!4 小时前
华为动态路由-OSPF-完全末梢区域
服务器·网络·华为
技术小齐4 小时前
网络运维学习笔记 016网工初级(HCIA-Datacom与CCNA-EI)PPP点对点协议和PPPoE以太网上的点对点协议(此处只讲华为)
运维·网络·学习
ITPUB-微风5 小时前
Service Mesh在爱奇艺的落地实践:架构、运维与扩展
运维·架构·service_mesh
落幕5 小时前
C语言-进程
linux·运维·服务器
chenbin5205 小时前
Jenkins 自动构建Job
运维·jenkins