如何手动释放linux内存

概述

  • /proc/sys/vm/drop_caches 是一个特殊的文件,通过向其中写入不同的值,可以告诉内核清理不同类型的缓存。这对于在不需要重启系统的情况下手动释放内存非常有用
  • 主要的清理类型包括页面缓存(pagecache)、目录项缓存(dentries)和 inode 缓存(inodes)

使用场景

  • 系统维护: 在进行系统维护之前,清理缓存可以确保系统从一个干净的状态开始,避免因为过多的缓存而导致不必要的性能问题
  • 性能测试: 在进行性能测试时,清理缓存可以使测试结果更加准确,确保系统的表现不会受到之前的缓存影响
  • 资源回收在系统内存资源紧张的情况下,清理缓存可以释放一部分内存,提供更多的可用内存供系统使用

使用示例

  • 在执行清理操作之前,确保没有正在进行的重要操作,以免清理缓存导致数据丢失或操作失败
  • 释放内存之前,建议执行 sync 将所有未写的系统缓冲区数据写入磁盘
[root@localhost ~]# sync
[root@localhost ~]# sync
[root@localhost ~]# cat /proc/sys/vm/drop_caches     #.默认0不清理缓存
0
  • 释放pagecache页缓存效果明显),这些缓存包含了最近被访问的文件的内容。执行后,系统将不再从缓存中读取这些文件,而是直接从磁盘上读取
[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:          32012       11439         313          30       20259       20144
Swap:         16127           4       16123

[root@localhost ~]# echo 1 > /proc/sys/vm/drop_caches
[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:          32012       11446       19923          30         642       20137
Swap:         16127           4       16123
  • 释放dentries和inodes缓存(效果不大),这对于释放文件系统元数据的内存占用非常有用
[root@localhost ~]# echo 2 > /proc/sys/vm/drop_caches 
[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:          32012       11283       20252          30         475       20353
Swap:         16127           4       16123
  • 释放所有缓存最彻底的清理操作),它将清除pagecache和dentries和inodes缓存,在需要释放尽可能多内存的情况下使用
  • 执行清理操作后,系统的性能可能会短暂下降,因为系统需要重新加载被清除的数据。因此,在生产环境中谨慎使用,并在合适的时机执行清理操作
[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:          32012       11439         313          30       20259       20144
Swap:         16127           4       16123

[root@localhost ~]# echo 3 > /proc/sys/vm/drop_caches 
[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:          32012       11271       20267          30         473       20365
Swap:         16127           4       16123
Copyright © www.sqlfans.cn 2023 All Right Reserved更新时间: 2024-07-05 22:28:20

results matching ""

    No results matching ""