Nodejs中http-proxy怎么那么消耗内存
Nodejs中http-proxy怎么那么消耗内存
3387: node proxy.js total used free shared buffers cached Mem: 502 497 5 0 3 41 -/+ buffers/cache: 452 50 Swap: 2047 692 1354
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 3387 root 16 0 673m 329m 3196 S 0.0 65.5 3:47.65 node
估计待会就要报错了
var options = { hostnameOnly: true, router: { ‘www.aa.com’: ‘127.0.0.1:3001’, ‘www.bb.com’’: ‘127.0.0.1:3001’ } }; require(“http-proxy”).createServer(options).listen(80); 无任何复杂逻辑 照搬 https://github.com/nodejitsu/node-http-proxy#proxy-requests-using-a-hostname-only-proxytable 求高手解决
运行一天服务器没挂掉 内存剩余可怜 访问速度超慢 重启 proxy 服务器 立马爽YY 我的网站基本没访问量 还处在测试阶段 求解决哦~~
我觉得,你去提issue 解决得更快…
内存消耗大的问题可能是由于 http-proxy
模块在处理大量请求时,累积了大量的内部缓存或者连接对象。你可以通过以下几种方式来优化:
- 设置代理表:确保代理表只包含必要的条目,避免不必要的域名映射。
- 增加垃圾回收:手动触发垃圾回收,确保不再使用的对象能够及时被释放。
- 限制并发请求:使用队列或者限流器来控制并发请求的数量。
示例代码
const http = require('http');
const httpProxy = require('http-proxy');
// 创建代理服务器
const proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:3001',
xfwd: true
});
// 限制并发请求的数量
let queue = [];
let processing = false;
function processQueue() {
if (processing || !queue.length) return;
processing = true;
const { req, res } = queue.shift();
proxy.web(req, res);
req.on('close', () => {
processing = false;
processQueue();
});
}
// 创建HTTP服务器
const server = http.createServer((req, res) => {
queue.push({ req, res });
processQueue();
});
server.listen(80, () => {
console.log('Proxy server listening on port 80');
});
解释
- 创建代理服务器:使用
http-proxy
的createProxyServer
方法创建一个简单的代理服务器。 - 限制并发请求:使用队列来管理请求,并通过
processQueue
函数来处理队列中的请求。每次处理完一个请求后,会检查是否有新的请求加入队列并继续处理。 - 监听端口:创建 HTTP 服务器并监听 80 端口。
通过这种方式,可以有效地控制并发请求的数量,减少内存占用。