當服務器內存超過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、最終測試

經過測試,能夠正常的識別當前內存使用率,並且內存超過80%後,執行清理redis緩存。

到此為止。

發布者:彬彬筆記,轉載請註明出處:https://www.binbinbiji.com/zh-hant/linux/3588.html

(0)
彬彬筆記彬彬筆記
上一篇 2024年12月12日 16:38
下一篇 2023年2月10日 11:06

相關推薦

發表回復

登錄後才能評論
蜀ICP備14017386號-13