场景介绍

一、通常情况   先来说说free命令。
[root@instance-2a85072t ~]# free -m
total used free shared buff/cache available
Mem: 1999 152 251 32 1595 1619
Swap: 0 0 0
[root@instance-2a85072t ~]#
提示:
total 内存总数
used 已经使用的内存数
free 空闲的内存数
shared 多个进程共享的内存总额
buff/cache 读写缓存内存,这部分内存是当空闲来用的,当free内存不足时,linux内核会将此内存释放
buffers Buffer Cache和cached Page Cache 磁盘缓存的大小
-buffers/cache (已用)的内存数:used - buffers - cached
+buffers/cache(可用)的内存数:free + buffers + cached
可用的memory=free memory+buffers+cached
available 还可以被 应用程序 使用的物理内存

手动释放缓存

清除pagecache
sync && echo 1 > /proc/sys/vm/drop_caches
# 清除回收slab分配器中的对象(包括目录项缓存和inode缓存)
# slab分配器是内核中管理内存的一种机制,其中很多缓存数据实现都是用的pagecache
sync && echo 2 > /proc/sys/vm/drop_caches
# 清除pagecache和slab分配器中的缓存对象
sync && echo 3 > /proc/sys/vm/drop_caches

定时清除过大buff/cache脚本(dropcaches.sh)

  1. #!/bin/bash
  2. LIMIT=1024
  3. LOG_FILE="/data/timing_dropcaches.log"
  4. #定时清理系统内存
  5. #https://blog.csdn.net/gaojinshan/article/details/40710369
  6. used=`free -m | awk 'NR==2' | awk '{print $3}'`
  7. free=`free -m | awk 'NR==2' | awk '{print $4}'`
  8. echo "===========================" >> $LOG_FILE
  9. date +"%Y-%m-%d %H:%M.%S" >> $LOG_FILE
  10. echo "Memory usage | [Use:${used}MB][Free:${free}MB] | limit[${LIMIT}MB]" >> $LOG_FILE
  11. # drop caches when the free memory less than 512M
  12. if [ $free -le $LIMIT ] ; then
  13. sync && echo 1 > /proc/sys/vm/drop_caches
  14. #sync && echo 2 > /proc/sys/vm/drop_caches
  15. #sync && echo 3 > /proc/sys/vm/drop_caches
  16. echo "OK" >> $LOG_FILE
  17. else
  18. echo "Not required" >> $LOG_FILE
  19. fi

将脚本添加到crond任务,定时执行;
crontab -e -u root
输入:/30 * /data/freemem.sh
检查任务列表:crontab -l
查看任务日志:tail -100f /var/log/cron