如何编写自动清理内存缓存的脚本

wen 实用脚本 2

本文目录导读:

如何编写自动清理内存缓存的脚本

  1. Linux 系统内存缓存清理脚本
  2. 定时自动清理方案
  3. Windows 内存清理脚本
  4. 安全建议和注意事项
  5. 使用方法
  6. 注意事项

我来为您介绍几种自动清理内存缓存的方法,根据使用场景提供不同的脚本方案。

Linux 系统内存缓存清理脚本

基础清理脚本

#!/bin/bash
# 文件名: clear_cache.sh
echo "=== 内存缓存清理脚本 ==="
echo "清理前内存使用情况:"
free -h
# 清理页面缓存
sync && echo 1 > /proc/sys/vm/drop_caches
# 清理目录项和inode缓存
echo 2 > /proc/sys/vm/drop_caches
# 清理所有缓存(页面缓存、目录项、inode)
echo 3 > /proc/sys/vm/drop_caches
echo "清理完成!"
echo "清理后内存使用情况:"
free -h

增强版清理脚本(带安全检查和日志)

#!/bin/bash
# 文件名: smart_clear_cache.sh
# 配置参数
MEMORY_THRESHOLD=80  # 内存使用率超过此值才清理
LOG_FILE="/var/log/cache_clear.log"
# 日志函数
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}
# 获取当前内存使用率
get_memory_usage() {
    free | grep Mem | awk '{print int($3/$2 * 100)}'
}
# 检查是否为root用户
if [[ $EUID -ne 0 ]]; then
    echo "错误:此脚本需要root权限运行"
    exit 1
fi
# 主逻辑
CURRENT_USAGE=$(get_memory_usage)
echo "当前内存使用率: ${CURRENT_USAGE}%"
if [ "$CURRENT_USAGE" -gt "$MEMORY_THRESHOLD" ]; then
    log_message "内存使用率 ${CURRENT_USAGE}%,超过阈值 ${MEMORY_THRESHOLD}%,开始清理"
    # 执行清理
    sync
    echo 3 > /proc/sys/vm/drop_caches
    log_message "缓存清理完成"
    echo "清理后内存使用情况:"
    free -h
else
    log_message "内存使用率 ${CURRENT_USAGE}%,未达阈值,跳过清理"
    echo "内存使用率正常,无需清理"
fi

定时自动清理方案

使用 crontab 设置定时任务

#!/bin/bash
# 设置定时清理脚本
# 创建清理脚本
cat > /usr/local/bin/auto_clear_cache.sh << 'EOF'
#!/bin/bash
sync
echo 3 > /proc/sys/vm/drop_caches
echo "$(date): Cache cleared" >> /var/log/cache_clear_cron.log
EOF
# 赋予执行权限
chmod +x /usr/local/bin/auto_clear_cache.sh
# 添加到 crontab(每天凌晨3点执行)
echo "0 3 * * * /usr/local/bin/auto_clear_cache.sh" | crontab -
# 验证是否设置成功
crontab -l

systemd 服务定时清理

# 创建 systemd 服务
cat > /etc/systemd/system/cache-cleaner.service << 'EOF'
[Unit]
Description=Memory Cache Cleaner Service
After=network.target
[Service]
Type=oneshot
ExecStart=/bin/bash -c 'sync && echo 3 > /proc/sys/vm/drop_caches'
User=root
Group=root
[Install]
WantedBy=multi-user.target
EOF
# 创建定时器
cat > /etc/systemd/system/cache-cleaner.timer << 'EOF'
[Unit]
Description=Run cache cleaner every 6 hours
[Timer]
OnCalendar=*-*-* 0,6,12,18:00:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
# 启动服务
systemctl daemon-reload
systemctl enable cache-cleaner.timer
systemctl start cache-cleaner.timer

Windows 内存清理脚本

PowerShell 脚本

# 文件名: Clear-Cache.ps1
Write-Host "=== Windows 内存缓存清理 ===" -ForegroundColor Green
# 显示当前内存使用情况
$os = Get-CimInstance Win32_OperatingSystem
$totalMemory = [math]::Round($os.TotalVisibleMemorySize/1024/1024, 2)
$freeMemory = [math]::Round($os.FreePhysicalMemory/1024/1024, 2)
$usedMemory = $totalMemory - $freeMemory
$usagePercent = [math]::Round(($usedMemory / $totalMemory) * 100, 2)
Write-Host "总内存: ${totalMemory}GB"
Write-Host "已使用: ${usedMemory}GB ($usagePercent%)"
Write-Host "可用: ${freeMemory}GB"
# 清理方式1:清空工作集
Write-Host "正在清理进程工作集..." -ForegroundColor Yellow
Get-Process | ForEach-Object {
    try {
        [System.GC]::Collect()
        [System.GC]::WaitForPendingFinalizers()
        if ($_.Responding) {
            $_.Refresh()
        }
    } catch {
        # 忽略无法访问的进程
    }
}
# 清理方式2:清空DNS缓存
Write-Host "正在清空DNS缓存..." -ForegroundColor Yellow
Clear-DnsClientCache
# 清理方式3:清空文件系统缓存
Write-Host "正在清理文件系统缓存..." -ForegroundColor Yellow
$EMPTY = @()
[System.IO.Directory]::GetLogicalDrives() | ForEach-Object {
    try {
        $drive = $_.TrimEnd('\')
        [System.IO.DriveInfo]::new($drive).TotalFreeSpace | Out-Null
    } catch {}
}
Write-Host "缓存清理完成!" -ForegroundColor Green
Write-Host "清理后内存使用情况:" -ForegroundColor Cyan
$os = Get-CimInstance Win32_OperatingSystem
$freeMemory = [math]::Round($os.FreePhysicalMemory/1024/1024, 2)
$usedMemory = $totalMemory - $freeMemory
$usagePercent = [math]::Round(($usedMemory / $totalMemory) * 100, 2)
Write-Host "已使用: ${usedMemory}GB ($usagePercent%)"
Write-Host "可用: ${freeMemory}GB"

批处理脚本 (CMD)

@echo off内存清理工具
color 0A
echo ========================================
echo         Windows 内存缓存清理工具
echo ========================================
echo.
echo 1. 清理前内存状态:
systeminfo | findstr /C:"可用物理内存"
echo.
echo 2. 正在清理系统缓存...
:: 清空DNS缓存
ipconfig /flushdns >nul 2>&1
echo     - DNS缓存已清理
:: 清空预读取文件
del /f /s /q "%windir%\Prefetch\*" >nul 2>&1
echo     - 预读取文件已清理
:: 清空临时文件
del /f /s /q "%temp%\*" >nul 2>&1
echo     - 临时文件已清理
echo.
echo 3. 清理完成!
echo.
echo 4. 清理后内存状态:
systeminfo | findstr /C:"可用物理内存"
echo.
pause

安全建议和注意事项

使用前检查清单

#!/bin/bash
# 安全检查脚本 pre_clear_check.sh
echo "=== 缓存清理前安全检查 ==="
# 检查1:确认是否需要清理
echo "检查1: 确认当前内存状况"
free -h
echo ""
# 检查2:检查重要进程
echo "检查2: 检查关键服务"
for service in mysql nginx apache2 redis; do
    if systemctl is-active --quiet $service 2>/dev/null; then
        echo "  - $service: 运行中"
    fi
done
echo ""
# 检查3:确认磁盘使用情况
echo "检查3: 检查磁盘使用"
df -h / | tail -1
echo ""
# 检查4:确认是否有足够的Swap空间
echo "检查4: 检查Swap使用"
swapon --show
echo ""
# 建议
echo "建议:"
echo "- 确保关键数据已持久化"
echo "- 确认应用可以承受缓存丢失"
echo "- 建议在低负载时段执行"

使用方法

Linux 系统

# 1. 赋予执行权限
chmod +x clear_cache.sh
# 2. 运行脚本
sudo ./clear_cache.sh
# 3. 设置定时任务(可选)
crontab -e
# 添加以下行(每天凌晨2点执行)
0 2 * * * /path/to/clear_cache.sh

Windows 系统

# 1. 以管理员身份运行 PowerShell
# 2. 执行脚本
.\Clear-Cache.ps1
# 3. 设置计划任务(可选)
# 使用任务计划程序添加定时任务

注意事项

  1. 谨慎使用:频繁清理缓存可能影响系统性能
  2. 权限要求:Linux需root权限,Windows需管理员权限
  3. 业务影响:清理前确保业务可接受短暂性能波动
  4. 监控告警:结合监控系统使用,避免过度清理
  5. 测试环境:先在测试环境验证效果

根据您的具体需求和系统环境选择合适的脚本方案。

抱歉,评论功能暂时关闭!