mongodb WiredTiger 内存分配

转载自勤奋的小青蛙

mongodb占用内存非常高,这是因为官方为了提升存储的效率,设计就这么设计的。

但是大部分的个人开发者所购买的服务器内存并没有那么大,所以,我们需要配置下MongoDB的内存缓存大小,不然mongodb会占用非常多。

官方的配置缓存项处文档是这么解释的:

WiredTiger Options

--wiredTigerCacheSizeGB number

New in version 3.0.

Defines the maximum size of the internal cache that WiredTiger will use for all data.

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

Changed in version 3.2: Starting in MongoDB 3.2, the WiredTiger internal cache, by default, will use the larger of either:

  • 60% of RAM minus 1 GB, or
  • 1 GB.

mongodb会尽可能的把所有的数据都缓存,以便提高效率。

以mongodb 3.2为例,WiredTiger内部缓存,默认会用掉

  • 60% * 内存 - 1GB
  • 1GB

当你的内存大于1GB,mongodb会用掉 内存的60% - 1GB 的内存作为缓存;

当你的内存小于1GB,mongodb会直接用掉1GB。

另外,MongoDB 3.4与3.2也是有区别的,MongoDB 3.4该配置项为:

storage.wiredTiger.engineConfig.cacheSizeGB

Type: float

The maximum size of the internal cache that WiredTiger will use for all data.

Changed in version 3.4: Values can range from 256MB to 10TB and can be a float. In addition, the default value has also changed.

Starting in 3.4, the WiredTiger internal cache, by default, will use the larger of either:

  • 50% of RAM minus 1 GB, or
  • 256 MB.

这样显然很不合理,对于大部分的个人开发,内存是宝贵的。所以,我们需要配置为MB。

配置项参考此处配置:WiredTiger cache size is only configurable in whole gigabytes.

下面是修改后的配置:/etc/mongod.conf

1
2
3
4
5
6
7
8
9
10
11
12
# Where and how to store data.
storage:
  dbPath: /var/lib/mongo
  #dbPath: /mongodata
  journal:
    enabled: true
#  engine:
  mmapv1:
    smallFiles: true
  wiredTiger:
    engineConfig:
      configString : cache_size=512M

其实重点就是下面一项,配置之后,重启mongodb生效:

1
2
3
wiredTiger:
    engineConfig:
      configString : cache_size=512M

原创文章,转载请注明: 转载自勤奋的小青蛙

发现一只32G内存的服务器,上边跑了几个 sharding 模式的 mongod,把内存吃到只剩下4G,8G swap 更是丁点不剩。

我见过吃内存的 mongod,可没见过大胃口的 mongod 啊。不过以前我也没怎么见到在这么大内存的机器上跑的 mongod。不过不管如何,把 swap 全吃掉总归是不对的。

于是翻了翻 mongodb 源码,发现出现这种情况还真是机器的配置的问题。代码里有这么一段(在 GitHub 上的位置):

 
wiredtiger_init.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
if (cacheSizeGB == 0) {
    // Since the user didn't provide a cache size, choose a reasonable default value.
    // We want to reserve 1GB for the system and binaries, but it's not bad to
    // leave a fair amount left over for pagecache since that's compressed storage.
    ProcessInfo pi;
    double memSizeMB = pi.getMemSizeMB();
    if (memSizeMB > 0) {
        double cacheMB = (memSizeMB - 1024) * 0.6;
        cacheSizeGB = static_cast<size_t>(cacheMB / 1024);
        if (cacheSizeGB < 1)
            cacheSizeGB = 1;
    }
}

大概这就是决定它自己要用多少内存的代码了。先留出1G,然后再留出40%,剩下的能吃就吃!于是,好几只 mongod 开始抢食了!默认vm.swappiness=60的内核看到内存快用完了,于是开始往 swap 挪。结果造成内核挪多少,mongod 吃多少……

这种情况在机器内存少的时候没有出现,大概是因为内存少的时候,mongod 留出的比例比较高,内核就没那么卖力地把数据往 swap 上挪了。而且这次是好几只 mongod 哄抢呢。

原文地址:https://www.cnblogs.com/xibuhaohao/p/11278052.html