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

wen 实用脚本 30

Linux 系统缓存清理

内存缓存清理

#!/bin/bash
# clean_mem_cache.sh
# 清理PageCache
sync && echo 1 > /proc/sys/vm/drop_caches
# 清理dentries和inodes
sync && echo 2 > /proc/sys/vm/drop_caches
# 清理所有缓存
sync && echo 3 > /proc/sys/vm/drop_caches
echo "内存缓存清理完成"

设置定时任务

# 每天凌晨3点执行
0 3 * * * /usr/local/bin/clean_mem_cache.sh
# 每6小时执行一次
0 */6 * * * /usr/local/bin/clean_mem_cache.sh

Redis 缓存清理

Redis 过期键清理脚本

#!/usr/bin/env python3
# clean_redis_cache.py
import redis
import time
def clean_redis_cache():
    # 连接Redis
    r = redis.Redis(host='localhost', port=6379, db=0)
    # 方式1:清理所有缓存
    r.flushdb()
    # 方式2:删除特定模式的键
    pattern = "session:*"  # 匹配以session:开头的键
    cursor = 0
    while True:
        cursor, keys = r.scan(cursor, match=pattern, count=100)
        if keys:
            r.delete(*keys)
        if cursor == 0:
            break
    # 方式3:清理过期键
    cursor = 0
    while True:
        cursor, keys = r.scan(cursor, count=100)
        for key in keys:
            # 检查TTL,如果已过期则删除
            if r.ttl(key) == -2:  # 键不存在
                continue
            elif r.ttl(key) == -1:  # 没有设置过期时间
                if should_delete(key):  # 自定义删除条件
                    r.delete(key)
        if cursor == 0:
            break
def should_delete(key):
    # 自定义删除逻辑
    # 删除特定前缀的键
    return key.startswith(b'temp:') or key.startswith(b'cache:')
if __name__ == "__main__":
    clean_redis_cache()

Nginx 缓存清理

Nginx 缓存清除脚本

#!/bin/bash
# clean_nginx_cache.sh
CACHE_PATH="/var/cache/nginx"
PURGE_PATH="/path/to/nginx-cache-purge"
echo "开始清理Nginx缓存..."
# 方法1:直接删除缓存文件
if [ -d "$CACHE_PATH" ]; then
    find $CACHE_PATH -type f -mtime +7 -delete  # 删除7天前的缓存
    find $CACHE_PATH -type d -empty -delete     # 删除空目录
    echo "Nginx缓存清理完成"
fi
# 方法2:使用缓存清除模块(需要ngx_cache_purge模块)
curl -X PURGE http://localhost/cache/purge/
# 方法3:重新加载nginx配置
nginx -s reload

应用程序缓存清理

PHP 缓存清理

#!/bin/bash
# clean_php_cache.sh
# 清理OPcache
if [ -f /usr/local/php/var/run/php-fpm.pid ]; then
    kill -SIGUSR2 $(cat /usr/local/php/var/run/php-fpm.pid)
fi
# 清理PHP会话文件
find /tmp -name "sess_*" -mtime +2 -delete
# 清理应用缓存目录
APP_CACHE_DIRS=(
    "/var/www/html/storage/cache"
    "/var/www/html/storage/framework/cache"
    "/var/www/html/bootstrap/cache"
)
for dir in "${APP_CACHE_DIRS[@]}"; do
    if [ -d "$dir" ]; then
        rm -rf $dir/*
        echo "已清理 $dir"
    fi
done

Docker 缓存清理

Docker 清理脚本

#!/bin/bash
# clean_docker_cache.sh
echo "开始清理Docker缓存..."
# 删除未使用的容器
docker container prune -f
# 删除未使用的镜像
docker image prune -a -f
# 删除未使用的网络
docker network prune -f
# 删除未使用的卷
docker volume prune -f
# 清理系统所有未使用资源
docker system prune -a --volumes -f
# 清理构建缓存
docker builder prune -f
echo "Docker缓存清理完成"

综合缓存清理脚本

#!/bin/bash
# comprehensive_cache_clean.sh
LOG_FILE="/var/log/cache_clean.log"
DATE=$(date '+%Y-%m-%d %H:%M:%S')
log_message() {
    echo "[$DATE] $1" >> $LOG_FILE
    echo "[$DATE] $1"
}
clean_memory_cache() {
    log_message "开始清理内存缓存..."
    sync
    echo 3 > /proc/sys/vm/drop_caches
    log_message "内存缓存清理完成"
}
clean_application_cache() {
    log_message "开始清理应用缓存..."
    # 清理临时文件
    find /tmp -type f -mtime +1 -delete
    # 清理日志文件
    find /var/log -name "*.log" -mtime +30 -delete
    # 清理会话文件
    find /var/lib/php/sessions -type f -mtime +1 -delete
    log_message "应用缓存清理完成"
}
clean_package_cache() {
    log_message "开始清理包管理器缓存..."
    # Ubuntu/Debian
    if command -v apt-get &> /dev/null; then
        apt-get clean
        apt-get autoclean
        apt-get autoremove -y
    fi
    # CentOS/RHEL
    if command -v yum &> /dev/null; then
        yum clean all
    fi
    log_message "包管理器缓存清理完成"
}
# 执行清理
clean_memory_cache
clean_application_cache
clean_package_cache
log_message "所有缓存清理完成"

智能缓存清理(带阈值)

#!/bin/bash
# smart_cache_clean.sh
# 设置阈值(百分比)
MEM_THRESHOLD=80
DISK_THRESHOLD=85
# 检查内存使用率
mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}' | cut -d. -f1)
# 检查磁盘使用率
disk_usage=$(df -h / | tail -1 | awk '{print $5}' | cut -d% -f1)
log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}
if [ $mem_usage -gt $MEM_THRESHOLD ] || [ $disk_usage -gt $DISK_THRESHOLD ]; then
    log_message "系统资源使用率过高(内存: ${mem_usage}%, 磁盘: ${disk_usage}%)"
    log_message "开始执行缓存清理..."
    # 清理内存缓存
    sync && echo 3 > /proc/sys/vm/drop_caches
    # 清理磁盘缓存
    find /var/cache -type f -atime +7 -delete 2>/dev/null
    log_message "缓存清理完成"
else
    log_message "系统资源使用正常(内存: ${mem_usage}%, 磁盘: ${disk_usage}%),无需清理"
fi

使用建议

  1. 设置定时任务
    # crontab -e 添加定时任务
    # 每天凌晨2点执行
    0 2 * * * /usr/local/bin/clean_mem_cache.sh

每4小时执行一次

0 /4 /usr/local/bin/clean_redis_cache.py

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


2. **权限设置**:
```bash
chmod +x /usr/local/bin/*.sh
chmod +x /usr/local/bin/*.py
  1. 日志记录:始终添加日志记录,便于排查问题

  2. 测试先行:先在测试环境运行,确认无误后再部署到生产环境

  3. 备份重要数据:清理前确认缓存内容是否可安全删除

请根据实际需求选择合适的脚本,并适当调整参数。

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