当服务器内存超过80%时,清空redis缓存

服务器的内存莫名其妙的涨很多,然后服务器就卡死了,现在搞个清理命令。

当服务器内存超过80%时,清空redis缓存。

服务器为:CentOS Stream 9 x86_64(Py3.12.3)

使用的是宝塔面板最新版本

1、服务器安装bc

sudo yum install bc

bc 是一个用于处理浮点数的命令行计算器,在脚本中用于比较内存使用率是否超过阈值

2、判断命令

服务器新建一个sh文件,比如:/www/server/redis/rediscleanall.sh,将下面的命令存放到sh文件中

注意:需要设置sh文件的权限,不然没有执行权限

#!/bin/bash

# 获取当前内存使用率
memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

# 设置内存使用阈值
threshold=80.0

# 输出当前内存使用率
echo "当前内存使用率: $memory_usage%"

# 检查内存使用率是否超过阈值
if (( $(echo "$memory_usage > $threshold" | bc -l) )); then
    echo "内存使用率超过80%,正在清空Redis缓存..."
    # 清空Redis缓存
    redis-cli flushall
else
    echo "内存使用率正常,未达到清空Redis缓存的条件。"
fi

如果你的 Redis 设置了密码,你需要在清空 Redis 缓存时提供密码。可以通过 redis-cli-a 选项来传递密码。修改脚本如下:

#!/bin/bash

# 获取当前内存使用率
memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

# 设置内存使用阈值
threshold=80.0

# Redis 密码
redis_password="your_redis_password"

# 输出当前内存使用率
echo "当前内存使用率: $memory_usage%"

# 检查内存使用率是否超过阈值
if (( $(echo "$memory_usage > $threshold" | bc -l) )); then
    echo "内存使用率超过80%,正在清空Redis缓存..."
    # 使用密码清空Redis缓存
    redis-cli -a $redis_password flushall
else
    echo "内存使用率正常,未达到清空Redis缓存的条件。"
fi

但是直接这样使用密码执行,会提示不安全:

Warning: Using a password with ‘-a’ or ‘-u’ option on the command line interface may not be safe.

下面是优化的代码

#!/bin/bash

# 获取当前内存使用率
memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

# 设置内存使用阈值
threshold=80.0

# Redis 密码
redis_password="your_redis_password"

# 输出当前内存使用率
echo "当前内存使用率: $memory_usage%"

# 设置 REDISCLI_AUTH 环境变量
export REDISCLI_AUTH=$redis_password

# 检查内存使用率是否超过阈值
if (( $(echo "$memory_usage > $threshold" | bc -l) )); then
    echo "内存使用率超过80%,正在清空Redis缓存..."
    # 清空Redis缓存
    redis-cli flushall
else
    echo "内存使用率正常,未达到清空Redis缓存的条件。"
fi

3、在宝塔面板设置定时任务

在宝塔面板设置定时任务,比如设置为每隔3分钟检测一次

当服务器内存超过80%时,清空redis缓存

4、最终测试

经过测试,能够正常的识别当前内存使用率,并且内存超过80%后,执行清理redis缓存。

到此为止。

发布者:彬彬笔记,转载请注明出处:https://www.binbinbiji.com/linux/3588.html

(0)
彬彬笔记彬彬笔记
上一篇 2024年12月12日 16:38
下一篇 4天前

相关推荐

发表回复

登录后才能评论
蜀ICP备14017386号-13