MongoDB在CentOS上的卡顿通常与硬件资源不足、配置不合理、查询效率低或索引缺失有关。以下是针对性的解决步骤,覆盖从基础到进阶的优化方向:
升级硬件配置
优化操作系统设置
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag
并将上述命令添加到/etc/rc.local中,确保开机生效。/etc/sysctl.conf,增加以下配置(优化网络和文件句柄限制):net.core.somaxconn = 65535 # 增加TCP连接队列长度
vm.swappiness = 10 # 减少Swap使用(值越低,越倾向于使用物理内存)
fs.file-max = 1000000 # 提升系统最大文件句柄数
执行sysctl -p使配置生效。/etc/security/limits.conf,添加以下内容(针对MongoDB用户):mongodb soft nofile 65535
mongodb hard nofile 65535
mongodb soft nproc 65535
mongodb hard nproc 65535
重启MongoDB服务后生效。调整WiredTiger缓存大小
WiredTiger是MongoDB的默认存储引擎,其缓存大小直接影响性能。编辑/etc/mongod.conf,设置cacheSizeGB为物理内存的50%-70%(避免占用过多内存导致系统交换):
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 8 # 示例:8GB内存分配给WiredTiger
重启服务使配置生效:systemctl restart mongod。
优化日志与持久化设置
operationProfiling模块记录执行时间超过阈值的查询,帮助定位性能瓶颈:operationProfiling:
mode: slowOp # 记录慢查询
slowOpThresholdMs: 100 # 慢查询阈值(毫秒)
syncPeriodSecs(默认100ms)可减少磁盘I/O,但会略微降低数据安全性:storage:
journal:
enabled: true
commitIntervalMs: 100 # 日志提交间隔(默认100ms,可根据需求调整)
/etc/mongod.conf:systemLog:
path: /var/log/mongodb/mongod.log
logAppend: true
logRotate: reopen # 支持日志轮转
结合logrotate工具(如/etc/logrotate.d/mongod)实现自动轮转。配置副本集与分片(大数据量必备)
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "192.168.1.101:27017" },
{ _id: 1, host: "192.168.1.102:27017" },
{ _id: 2, host: "192.168.1.103:27017" }
]
})
user_id、timestamp),避免数据倾斜(如避免使用单调递增的字段作为分片键)。创建高效索引
email字段查询用户,执行:db.users.createIndex({ email: 1 }) // 1表示升序索引
status=1 AND create_time>='2025-01-01'),创建复合索引:db.orders.createIndex({ status: 1, create_time: -1 }) // 覆盖查询条件
db.collection.getIndexes()检查并删除未使用的索引。优化查询语句
db.users.find({ status: 1 }, { name: 1, email: 1, _id: 0 }) // 仅返回name和email
skip()(性能随页数增加而下降),改用基于范围的分页(如记录上次查询的_id):// 第一页
db.orders.find().sort({ _id: 1 }).limit(10)
// 第二页(假设上一页最后一条记录的_id为123)
db.orders.find({ _id: { $gt: 123 } }).sort({ _id: 1 }).limit(10)
explain()方法分析查询计划,确保查询使用了索引:db.users.find({ email: "test@example.com" }).explain("executionStats")
若winningPlan中stage为COLLSCAN(全表扫描),需优化索引。定期监控性能
mongostat(查看每秒操作数、读写延迟)、mongotop(查看集合级读写时间)实时监控性能。定期维护数据库
reIndex命令:db.users.reIndex()
mongodump和mongorestore定期备份,避免数据丢失。通过以上步骤,可系统性解决CentOS上MongoDB的卡顿问题。需注意的是,优化效果因业务场景而异,建议在测试环境中验证后再应用于生产环境。