mongo占用内存过大解决方案
問題出現
自己有一個測試用的服務器,配置很低。年前出現幾次問題,重啟后就好了也就沒注意。后來越來越頻繁就調查了一下,發現重啟后內存就一直增長直到接近100%。使用ps aux查看cpu和內存使用情況,發現mongo占用了大部分的內存,這是什么情況?
mongo3.2
因為服務器搭建有些年頭了,mongo的版本一致沒升級,停留在3.2版本上。查閱相關資料發現是默認設置導致的,mongo3.2有一段官方描述如下:
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.簡單來說就是內存占用在下面兩種情況中取最大值:
1、RAM的60%,并且這個60%要大于1GB
2、1GB
因為我的服務器是測試用,所以配置很低內存只有1GB,也就是說mongo默認就要全占了,怪不得內存一直100%。
但是mongo配置是可以改動的,有兩種方式。
一種是修改mongod.conf文件,設置cacheSizeGB參數:
... storage:dbPath: /var/lib/mongodbjournal:enabled: truewiredTiger:engineConfig:cacheSizeGB: xx ...另外一種就是如果使用命令啟動,那么啟動時可以添加參數:
--wiredTigerCacheSizeGB=xx但是!
mongo的3.2版本這個cacheSizeGB參數是int類型,如果使用小數就會報錯
Error parsing option “wiredTigerCacheSizeGB” as int: Bad digit “.” while parsing 0.3
所以最低只能是1GB!這樣我這種低配服務器就沒戲了。。。
mongo3.4
應該是官方也意思到這個問題了,所以在mongo的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.
可以看到,在這個版本中cacheSizeGB類型變成float了,也就是說可以用小數了。
而且默認配置也發生了改變:
1、50%的RAM,同樣要求這50%大于1GB
2、256M
簡單來說就是如果RAM大于2GB,就取50%。否則就直接使用256M,而且我們自定義的時候可以使用小數,這樣就非常合理了。
解決
這樣我們先將mongo升級到3.4及以上版本即可。
如果要自己配置的話,也需要先停止mongo,官方的做法是通過命令mongo進入數據庫,然后
> use admin; --使用管理員數據庫 > db.shutdownServer();然后可以通過上面提到的兩種方式進行修改:
1、修改mongod.conf文件,重啟mongo
2、使用命令啟動mongo的同時添加wiredTigerCacheSizeGB參數
總結
以上是生活随笔為你收集整理的mongo占用内存过大解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装使用Frida在Android上进行
- 下一篇: 部署nodejs项目到服务器的一些总结