在 Linux 上部署 MongoDB 时,“限流”通常可以从 网络层、系统资源层、MongoDB 自身配置层 三个层面来做。下面按常见场景给你一个实操清单。
在 mongod.conf 中:
net:
maxIncomingConnections: 1000
默认一般是 65536,生产环境建议按业务压测结果设置。
重启生效:
systemctl restart mongod
查看当前连接数:
db.serverStatus().connections
operationProfiling:
mode: slowOp
slowOpThresholdMs: 100
结合索引优化,避免慢查询占满资源。
连接字符串示例:
mongodb://host1,host2,host3/?readPreference=secondary
tc 限制 MongoDB 端口带宽(网络限流)例如限制 27017 端口为 10Mbps:
tc qdisc add dev eth0 root tbf rate 10mbit burst 32kbit latency 400ms
或按端口(需要 iptables + tc 配合,较复杂)。
systemd 限制资源(CPU / 内存)编辑:
systemctl edit mongod
加入:
[Service]
MemoryMax=4G
CPUQuota=200%
生效:
systemctl daemon-reload
systemctl restart mongod
ulimit 限制文件句柄MongoDB 很吃 fd:
ulimit -n 64000
写入 /etc/security/limits.conf:
mongod soft nofile 64000
mongod hard nofile 64000
以 Node.js 为例:
mongoose.connect(uri, {
maxPoolSize: 50
});
Java:
spring.data.mongodb.connection-pool.max-size=50
❌ MongoDB 没有内置 QPS 限流
❌ maxIncomingConnections 不等于 QPS 限制
❌ 只靠 Linux 限流容易误杀正常请求
✅ MongoDB:
maxIncomingConnections✅ 系统:
systemd 资源限制ulimit✅ 应用:
如果你能补充说明:
我可以直接给你可复制的配置模板。