linux buff/cache过大,清理脚本

三条指令:

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的官方文档):

[plain]  view plain  copy
  1. Writing to this will cause the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.  
  2. To free pagecache:  
  3. * echo 1 > /proc/sys/vm/drop_caches  
  4. To free dentries and inodes:  
  5. * echo 2 > /proc/sys/vm/drop_caches  
  6. To free pagecache, dentries and inodes:  
  7. * echo 3 > /proc/sys/vm/drop_caches  
  8. 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.  
  9. This tunable was added in 2.6.16.  

注意:在执行这三条命令前先执行sync命令


解决方案(自动)

1、编写shell定时任务脚本freemem.sh

[plain]  view plain  copy
  1. #! /bin/sh  
  2. used=`free -m | awk 'NR==2' | awk '{print $3}'`  
  3. free=`free -m | awk 'NR==2' | awk '{print $4}'`  
  4. echo "===========================" >> /app/memory/logs/mem.log  
  5. date >> /app/memory/logs/mem.log  
  6. echo "Memory usage before | [Use:${used}MB][Free:${free}MB]" >> /app/memory/logs/mem.log  
  7. if [ $free -le 4000 ] ; then  
  8.                 sync && echo 1 > /proc/sys/vm/drop_caches  
  9.                 sync && echo 2 > /proc/sys/vm/drop_caches  
  10.                 sync && echo 3 > /proc/sys/vm/drop_caches  
  11.                 used_ok=`free -m | awk 'NR==2' | awk '{print $3}'`  
  12.                 free_ok=`free -m | awk 'NR==2' | awk '{print $4}'`  
  13.                 echo "Memory usage after | [Use:${used_ok}MB][Free:${free_ok}MB]" >> /app/memory/logs/mem.log  
  14.                 echo "OK" >> /app/memory/logs/mem.log  
  15. else  
  16.                 echo "Not required" >> /app/memory/logs/mem.log  
  17. fi  
  18. exit 1  

2、使用crontab -e命令编辑当前用户的crontab

[plain]  view plain  copy
  1. 0 6 * * * /usr/local/tomcat/sztFileFront/bin/freemem.sh  

定时任务编写参考:http://www.jb51.net/article/15008.htm


3、重启crond服务

[plain]  view plain  copy
  1. /sbin/service crond restart  

4、查看crond服务是否重启成功

[plain]  view plain  copy
  1. /sbin/service crond status  



最后,问题解决。我设定的定时任务是每天早上6点执行一次freemem.sh脚本。
  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值