mongodb 3.2配置內存緩存大小為MB/MongoDB 3.x內存限制配置
轉載自勤奮的小青蛙
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 上的位置):
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 哄搶呢。