Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 釋放記憶體緩存命令詳解:drop_caches 參數 1/2/3 差異與定時清理腳本

編輯:關於 Linux

Linux 核心將閒置記憶體用作頁面緩存、目錄項、索引節點以加速 I/O,長時間運行導致可用記憶體極低、觸發 Swap 影響效能。透過 /proc/sys/vm/drop_caches 可手動或定時釋放緩存,本文詳細說明三種釋放等級、手動指令、自動化腳本與 crontab 部署。

記憶體緩存釋放示意圖

crontab 定時清理設定

drop_caches 三個等級

值動作影響範圍
0不釋放 (預設)無
1釋放頁面緩存Page Cache (檔案內容緩存)
2釋放目錄項與索引節點dentries + inodes (檔案系統元資料)
3釋放所有上述緩存Page Cache + dentries + inodes

建議:生產環境優先使用 1,僅在記憶體極度緊張時使用 3。釋放前務必執行 sync 將髒頁寫回磁碟,避免資料遺失。

手動釋放指令

# 釋放頁面緩存
sync && echo 1 > /proc/sys/vm/drop_caches

# 釋放 dentries/inodes
sync && echo 2 > /proc/sys/vm/drop_caches

# 釋放全部 (需 root)
sync && echo 3 > /proc/sys/vm/drop_caches

# sudo 環境寫法
sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"

自動化清理腳本 clear_cache.sh

#!/bin/bash
# 寫入磁碟確保資料一致性
sync
# 釋放頁面緩存
echo 1 > /proc/sys/vm/drop_caches
sync
# 釋放全部緩存 (視情況啟用)
# echo 3 > /proc/sys/vm/drop_caches

# 記錄清理前後記憶體狀態
free -m >> /var/log/clear_cache.log
date >> /var/log/clear_cache.log
echo "---" >> /var/log/clear_cache.log

部署定時任務

chmod +x /root/clear_cache.sh
# 每天凌晨 3 點執行
echo "0 3 * * * /root/clear_cache.sh" >> /var/spool/cron/root
# 或使用 crontab -e 編輯

效能影響與最佳實踐

  • 頻繁清理緩存反而降低 I/O 效能,核心會自動回收記憶體應對壓力
  • 僅在明確觀察到 Swap 持續增長、應用回應變慢時考慮清理
  • 資料庫伺服器 (MySQL/PostgreSQL) 建議調整 innodb_buffer_pool_size、shared_buffers 等專用緩存參數,而非依賴 OS 級清理
  • 監控指標:free -m、vmstat 1、sar -r 觀察 cached/buffers/swap used 趨勢
Copyright © Windows教程網 All Rights Reserved