MongoDB在3.2版本之后默认采用的WiredTiger存储引擎,可以通过cacheSizeGB参数设置内存上限。

刚开始使用MongoDB的时候没有特别在意他的内存占用情况,想当然的和MySQL做了先入为主的中和,当然最主要的还是因为是小白一枚,但是后来使用过程中发现,MongoDB内存占用是非常大的。

从官方文档可以得知,如果不设置cacheSizeGB内存,一个mongod实例几乎要占用服务器上一半的内存,也就是说,如果在同一台服务器上同时开两个或以上mongod实例,那么很大可能会发生内存不足而异常退出。

Memory Use

With WiredTiger, MongoDB utilizes both the WiredTiger internal cache and the filesystem cache.

Starting in MongoDB 3.4, the default WiredTiger internal cache size is the larger of either:

50% of (RAM - 1 GB), or

256 MB.

By default, WiredTiger uses Snappy block compression for all collections and prefix compression for all indexes. Compression defaults are configurable at a global level and can also be set on a per-collection and per-index basis during collection and index creation.

Different representations are used for data in the WiredTiger internal cache versus the on-disk format:

Data in the filesystem cache is the same as the on-disk format, including benefits of any compression for data files. The filesystem cache is used by the operating system to reduce disk I/O.

Indexes loaded in the WiredTiger internal cache have a different data representation to the on-disk format, but can still take advantage of index prefix compression to reduce RAM usage. Index prefix compression deduplicates common prefixes from indexed fields.

Collection data in the WiredTiger internal cache is uncompressed and uses a different representation from the on-disk format. Block compression can provide significant on-disk storage savings, but data must be uncompressed to be manipulated by the server.

Via the filesystem cache, MongoDB automatically uses all free memory that is not used by the WiredTiger cache or by other processes.

在使用的过程中,一直发现一个问题,给一个实例配置20G的内存上限,在过一段时间,或者突然有大量的操作时,实际使用内存(机器层面res)远远大于开始实例分配的内存,而且基本上会一直保持这个状态,可以自动回收的也只是一点点。每次都是通过重启MongoDB解决问题,很暴力~~

配置情况

....

directoryPerDB: true

engine: wiredTiger

wiredTiger:

engineConfig:

cacheSizeGB: 20

directoryForIndexes: true

collectionConfig:

blockCompressor: zlib

indexConfig:

prefixCompression: true

....

MongoDB进程实际上占用的系统内存情况

也可以通过mongostat监控内存使用情况

所以我一直困惑MongoDB的内存使用情况,最近终于揭开谜团。

cacheSizeGB包含的数据和索引的内存,MongoDB产生的连接池堆栈以及sorting buffer的内存都是额外占用系统内存的。

MongoDB在数据解压过程中会尽可能的占用系统内存,只要机器还有空闲内存可以用,就会使用,但是这个占用的内存不包含在cacheSizeGB设置的内存中,MongoDB进程也不会一直霸占这部分内存不释放,如果有其他的应用需要用到这个内存,MongoDB也会释放掉这部分内存提供给其他实例使用。

wiredTiger对内存使用会分为两大部分,一部分是内部内存,另外一部分是文件系统的缓存。

内部内存默认值有一个计算公式{ 50% of(RAM-1GB) ,or256MB },索引和集合的内存都被加载到内部内存,索引是被压缩的放在内部内存,集合则没有压缩。

wiredTiger会通过文件系统缓存,自动使用其他所有的空闲内存,放在文件系统缓存里面的数据,与磁盘上的数据格式一致,可以有效减少磁盘I/O。

后端写mongodb的服务内存溢出 mongodb 内存_后端写mongodb的服务内存溢出