linux buff/cache過大,清理指令碼
阿新 • • 發佈:2019-01-21
三條指令:
sync
echo 1 > /proc/sys/vm/drop_caches
echo 2 > /proc/sys/vm/drop_caches
echo 3 > /proc/sys/vm/drop_caches
執行完這三條指令後通過free -m命令檢視,free可用記憶體馬上增多,buff/cache列值變小,說明記憶體被釋放了,但是不能總是手動的執行這三條指令,所以最後寫了一個shell指令碼,開啟Linux定時任務crond,每天早上檢查一次free記憶體,當小於4G時執行這三條命令(注:系統內容20G)。
注意:在執行這三條命令之前一定要先執行sync命令(描述:sync 命令執行 sync 子例程。如果必須停止系統,則執行sync 命令以確保檔案系統的完整性。sync 命令將所有未寫的系統緩衝區寫到磁碟中,包含已修改的 i- Node、已延遲的塊 I/O 和讀寫對映檔案)
解決方案(手動)
1. 修改/proc/sys/vm/drop_caches,釋放Slab佔用的cache記憶體空間(參考drop_caches的官方文件):
- Writing to this will cause the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.
- To free pagecache:
- * echo 1 > /proc/sys/vm/drop_caches
- To free dentries and inodes:
- * echo 2 > /proc/sys/vm/drop_caches
- To free pagecache, dentries and inodes:
- * echo 3 > /proc/sys/vm/drop_caches
- As this is a non-destructive operation, and dirty objects are notfreeable, the user should run "sync" first in order to make sure allcached objects are freed.
- This tunable was added in 2.6.16.
注意:在執行這三條命令前先執行sync命令
解決方案(自動)
1、編寫shell定時任務指令碼freemem.sh
- #! /bin/sh
- used=`free -m | awk 'NR==2' | awk '{print $3}'`
- free=`free -m | awk 'NR==2' | awk '{print $4}'`
- echo "===========================" >> /app/memory/logs/mem.log
- date >> /app/memory/logs/mem.log
- echo "Memory usage before | [Use:${used}MB][Free:${free}MB]" >> /app/memory/logs/mem.log
- if [ $free -le 4000 ] ; then
- sync && echo 1 > /proc/sys/vm/drop_caches
- sync && echo 2 > /proc/sys/vm/drop_caches
- sync && echo 3 > /proc/sys/vm/drop_caches
- used_ok=`free -m | awk 'NR==2' | awk '{print $3}'`
- free_ok=`free -m | awk 'NR==2' | awk '{print $4}'`
- echo "Memory usage after | [Use:${used_ok}MB][Free:${free_ok}MB]" >> /app/memory/logs/mem.log
- echo "OK" >> /app/memory/logs/mem.log
- else
- echo "Not required" >> /app/memory/logs/mem.log
- fi
- exit 1
2、使用crontab -e命令編輯當前使用者的crontab
- 0 6 * * * /usr/local/tomcat/sztFileFront/bin/freemem.sh
3、重啟crond服務
- /sbin/service crond restart
4、檢視crond服務是否重啟成功
- /sbin/service crond status
最後,問題解決。我設定的定時任務是每天早上6點執行一次freemem.sh指令碼。