shell脚本清理redis模糊匹配的多个key,并计算释放内存大小

#!/bin/bash

# 定义Redis服务器地址和端口
REDIS_HOST="localhost"
REDIS_PORT=6380

# 获取Redis当前内存使用量(以字节为单位)
function get_redis_memory_usage() {
  redis-cli -h $REDIS_HOST -p $REDIS_PORT INFO memory | grep "used_memory:" | cut -d: -f2 | tr -d '\r'
}

# 删除匹配的键
function delete_matching_keys() {
  local key_pattern="$1"
  local keys=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT -n 0 KEYS "$key_pattern")
  local keys_count=$(echo "$keys" | wc -l)

  if [ "$keys_count" -eq 0 ]; then
    echo "没有找到匹配的键: $key_pattern"
    return
  fi

  # 统计待删除的总键数
  total_keys_to_delete=$((total_keys_to_delete + keys_count))
  keys_to_delete+="$keys "
}

# 定义匹配键的模式列表
KEY_PATTERNS=("saas_kline.*" "saas_depth.*" "saas_trade.*" "saas_ticker.*" "saas_depth20.*" "saas_mark_price.*" "saas_ticker_arr.*" "symbol_receiving_time" "jp_market:websocket:sub:*")

# 初始化待删除键统计
total_keys_to_delete=0
keys_to_delete=""

# 记录清理前的内存使用量
initial_memory=$(get_redis_memory_usage)

# 逐个处理每个匹配模式
for pattern in "${KEY_PATTERNS[@]}"; do
  delete_matching_keys "$pattern"
done

# 记录清理后的内存使用量
final_memory=$(get_redis_memory_usage)

# 显示所有匹配的键和键的数量
echo -e "$keys_to_delete"
echo "找到 $total_keys_to_delete 个匹配的键"

# 等待用户确认
echo -n "你确定要删除以上键吗?(y/n): "
read -r confirm_delete

if [ "$confirm_delete" == "y" ]; then
  # 最终删除所有匹配的键
  while IFS= read -r key; do
    key=$(echo "$key" | tr -d '\n') # 去掉换行符
    redis-cli -h $REDIS_HOST -p $REDIS_PORT -n 0 DEL "$key" > /dev/null
    echo "正在删除 $key"
  done <<< "$keys_to_delete"

  # 计算内存差值(以字节为单位)并取绝对值
  memory_freed_kb=$((initial_memory - final_memory))
  memory_freed_kb_abs=$((memory_freed_kb < 0 ? -memory_freed_kb : memory_freed_kb))

  echo "已删除 $total_keys_to_delete 个键"
  echo "已释放内存: $memory_freed_kb_abs 字节"
else
  echo "操作已取消"
fi

shell脚本清理redis模糊匹配的多个key,并计算释放内存大小_第1张图片

你可能感兴趣的:(shell,Bash,redis,缓存)