三条指令:
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
定时任务编写参考:http://www.jb51.net/article/15008.htm
3、重启crond服务
- /sbin/service crond restart
4、查看crond服务是否重启成功
- /sbin/service crond status

最后,问题解决。我设定的定时任务是每天早上6点执行一次freemem.sh脚本。
转载:https://blog.csdn.net/taozhe666/article/details/80744941?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&dist_request_id=2f676b1a-a2b0-46da-801f-12233922d582&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control
linux buff/cache过大,清理脚本
原文:https://www.cnblogs.com/yyhhblog/p/14420551.html