龙空技术网

linux 在服务器内存满的时候怎么临时清理缓存(drop_caches)

波波说运维 1563

前言:

现时同学们对“linux缓存服务器”都比较注意,同学们都需要了解一些“linux缓存服务器”的相关知识。那么小编同时在网络上搜集了一些对于“linux缓存服务器””的相关知识,希望咱们能喜欢,各位老铁们快快来了解一下吧!

概述

读写文件时,Linux内核为了提高读写效率与速度,会将文件在内存中进行缓存,这就是Cache Memory(缓存内存)。

即使程序运行结束后,Cache Memory也不会自动释放。这就会导致程序频繁读写文件后,可用物理内存会很少。

其实这缓存内存(Cache Memory)在你需要使用内存的时候会自动释放,所以不必担心没有内存可用。

如果你希望手动去释放Cache Memory(缓存内存)的话也是有办法的。

drop_caches

# cat /proc/sys/vm/drop_caches

0 //默认是0;1-清空页缓存;2-清空inode和目录树缓存;3-清空所有缓存

[root@bak ~]# sync //注意:在清空缓存之前使用sync命令同步数据到磁盘[root@bak ~]# free -m total used free shared buffers cachedMem: 15898 3029 12869 0 191 1064-/+ buffers/cache: 1772 14125Swap: 31999 0 31999

清空所有缓存

[root@bak ~]# echo 3 > /proc/sys/vm/drop_caches

查看内存

[root@bak ~]# free -m //发现缓存明显减少了 total used free shared buffers cachedMem: 15898 1770 14128 0 1 30-/+ buffers/cache: 1738 14160Swap: 31999 0 31999
附录

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_cachesTo free dentries and inodes:* echo 2 > /proc/sys/vm/drop_cachesTo free pagecache, dentries and inodes:* echo 3 > /proc/sys/vm/drop_cachesAs 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.

修改/etc/sysctl.conf 添加如下选项后就不会内存持续增加

vm.dirty_ratio = 1vm.dirty_background_ratio=1vm.dirty_writeback_centisecs=2vm.dirty_expire_centisecs=3vm.drop_caches=3vm.swappiness =100vm.vfs_cache_pressure=163vm.overcommit_memory=2vm.lowmem_reserve_ratio=32 32 8kern.maxvnodes=3
总结:

上面的设置比较粗暴,使cache的作用基本无法发挥。需要根据机器的状况进行适当的调节寻找最佳的折衷。而且一般是用来临时解决内存不足的问题,工作中还是经常会用到的,大家可以测试下。

标签: #linux缓存服务器 #linux服务器缓存过多怎么清理 #linux内存缓存 #linux服务器内存释放 #linux系统缓存高原因排查