Last active
October 8, 2019 17:34
-
-
Save dbernheisel/33e69acc1d2d27b0a1c61c7e55953822 to your computer and use it in GitHub Desktop.
Expire redis keys en-masse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Mass expire Redis keys using the SCAN command so it doesn't block or overwhelm | |
# memory | |
# Usage example: ./mass-expire-redis.sh "127.0.0.1" "6379" "mykey:*" "300" | |
# Logs to ./filename.ext.log | |
if [ $# -ne 4 ]; then | |
echo "Usage: $0 <host> <port> <pattern> <expiration>" | |
exit 1 | |
fi | |
HOST=$1; shift | |
PORT=$1; shift | |
PATTERN=$1; shift | |
TTL=$1; shift | |
COUNT=100 | |
CURSOR=0 | |
TOTAL=0 | |
LOG="$0.log" | |
expire_keys() { | |
read -rd ' ' CURSOR KEYS <<< \ | |
"$(redis-cli -h "$HOST" -p "$PORT" SCAN $CURSOR MATCH "$PATTERN" COUNT $COUNT)" | |
KEYS_COUNT=$(wc -l <<< "$KEYS") | |
TOTAL=$(( TOTAL + KEYS_COUNT )) | |
printf "Total %s \t | Page of %s: " "$TOTAL" "$KEYS_COUNT" | |
PROCESSED=0 | |
ALREADY_TTL=0 | |
while read -r KEY; do | |
[ "$KEY" = "" ] && continue | |
CURRENT_TTL="$(redis-cli -h "$HOST" -p "$PORT" <<< "TTL $KEY" | awk '{print $NF}')" | |
if [ "$CURRENT_TTL" = "-1" ]; then | |
EXPIRE_COMMAND="EXPIRE $KEY $TTL" | |
echo "$EXPIRE_COMMAND" >> "$LOG" | |
redis-cli -h "$HOST" -p "$PORT" <<< "$EXPIRE_COMMAND" &>> "$LOG" | |
(( PROCESSED++ )) | |
else | |
(( ALREADY_TTL++ )) | |
fi | |
done <<< "$KEYS" | |
printf "Set TTL for %s, %s already set\n" "${PROCESSED-0}" "${ALREADY_TTL-0}" | |
if [ "$CURSOR" -ne 0 ]; then | |
expire_keys | |
fi | |
} | |
date > "$LOG" | |
expire_keys |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
testing: