1. 程式人生 > 其它 >釋放linux的swap記憶體

釋放linux的swap記憶體

技術標籤:運維

這裡寫圖片描述
如上圖,一般情況下不會用到swap的,一般實體記憶體使用在90%以上(預設是這個數,可以自行在/etc/sysctl.conf裡設定vm.swappiness引數),但有的時候,記憶體會被快取佔用,導致系統開始使用swap空間,此時就需要清理下swap了
這裡先說下vm.swappiness引數,設定成vm.swappiness=10:就是說當記憶體使用90%以上才會使用swap空間

風險:
機器必須有足夠多的實體記憶體,否則貿然swapon/swapoff會導致OOM隨機kill掉程序從而出現問題;

The kernel attempts to remove all swap files/partitions that it currently has active. To do this, it needs to move all the data that is stored in the swap files back into RAM. Since a lot of RAM is often used for buffer cache, at least on Linux, trying to find space in RAM for the pages that were swapped out means flushing buffers and dumping disk cache, which may cause writes to disk. Depending on how much the the space being used by disk buffers is dirty, it could take a while to turn off large amounts of swap space that is has significant portions of it used, because of the possibility of significant disk activity.

原理:
swapoff -a的時候,核心嘗試刪除處於活動狀態的交換檔案或分割槽,為此它需要將儲存在交換檔案中的所有資料移回RAM。 通常情況下,Linux上大量的RAM用於緩衝區快取,Linux會嘗試在RAM上查詢已換出的頁面空間,這意味著重新整理緩衝區,並交換出磁碟快取(寫入硬碟)。這可能導致大量的IO;根據有交換分割槽的大小,可能需要一定時間才能關閉完交換空間;

所以建議操作前清理下快取

除此之外沒有其他影響;

第一步:先執行sync命令

#sync
  • 1

sync命令用於強制被改變的內容立刻寫入磁碟,更新超塊資訊,以防止釋放,sync命令則可用來強制將記憶體緩衝區中的資料立即寫入磁碟中。

第二步:(如果僅僅是清理swap的話,這一步可以不執行)

#echo 3 > /proc/sys/vm/drop_caches
  • 1

此指令輸入立即生效,意在釋放所有快取。
關於drop_caches:
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_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.
**echo 1:釋放頁面快取
echo 2:釋放目錄檔案和inodes
echo 3:釋放所有快取(頁面快取,目錄檔案和inodes)**
如下圖是執行完echo3 的cache的對比:
這裡寫圖片描述

第三步:關閉swap,再開戶swap

#swapoff -a
#swapon -a
  • 1
  • 2

這裡寫圖片描述
現在看swap的used的那一項為零了,說明已經清空