Redis 優化之內存分配控制 vm.overcommit_memory

 

vm.overcommit_memory


Redis在啓動時可能會出現這樣的日誌:

WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. 
To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf 
and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.

在分析這個問題之前, 首先要弄清楚什麼是overcommit? Linux操作系統對大部分申請內存的請求都回復yes, 以便能運行更多的程序。 因爲申請內存後, 並不會馬上使用內存, 這種技術叫做overcommit。 如果Redis在啓動時有上面的日誌, 說明vm.overcommit_memory=0, Redis提示把它設置爲1。
vm.overcommit_memory用來設置內存分配策略, 有三個可選值, 如表:可用內存代表物理內存與swap之和

日誌中的Background save代表的是bgsave和bgrewriteaof, 如果當前可用內存不足, 操作系統應該如何處理fork操作。 如果
vm.overcommit_memory=0, 代表如果沒有可用內存, 就申請內存失敗, 對應到Redis就是執行fork失敗, 在Redis的日誌會出現:

Cannot allocate memory

Redis建議把這個值設置爲1, 是爲了讓fork操作能夠在低內存下也執行成功。
 

 

獲取和設置


獲取:

[root@localhost ~]# cat /proc/sys/vm/overcommit_memory 
0

設置:
 

[root@localhost ~]# echo "vm.overcommit_memory=1" >> /etc/sysctl.conf 
[root@localhost ~]# sysctl vm.overcommit_memory=1
vm.overcommit_memory = 1
[root@localhost ~]# cat /proc/sys/vm/overcommit_memory 
1

 

最佳實踐


·Redis設置合理的maxmemory, 保證機器有20%~30%的閒置內存。
·集中化管理AOF重寫和RDB的bgsave。
·設置vm.overcommit_memory=1, 防止極端情況下會造成fork失敗。
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章