server.js
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
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
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}`);
});
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » nodejs 服务器实现负载均衡
发表评论 取消回复