在Linux下经常会遇到buff/cache内存占用过多问题,尤其是使用云主机的时候最严重,由于很多是虚拟内存,因此如果buff/cache占用过大的,free空闲内存就很少,影响使用;
通常内存关系是:
普通机器:total=used+free
虚拟机器:total=used+free+buff/cache
现在给大家演示一下,我找了台虚拟机,当然,现在的buff/cache不是很大
在操作之前,要先sync一下,刷新下缓存,避免出现意外(描述:sync 命令运行 sync 子例程。如果必须停止系统,则运行sync 命令以确保文件系统的完整性。sync 命令将所有未写的系统缓冲区写到磁盘中,包含已修改的 i-Node、已延迟的块 I/O 和读写映射文件)
然后使用命令清除cache缓存
通过3次清除,可以看到内存增加了
这个1、2、3分别是什么意思,自己看官方文档吧
- 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.
当然,再拓展一下,你也可以写个自动化的脚本,更有意思
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