Select Page

Recently we had issues with Redis acting up, so i got this maintenance script going, that checks the Redis availability and resets it, if it becomes unavailable. Hope it helps

#!/bin/bash

LOG_FILE=”redis.log”

# Function to log a message with date and time
function log_message() {
local message=”$1″
echo “$(date ‘+%Y-%m-%d %H:%M:%S’) – $message” >> “$LOG_FILE”
}

# Function to check if Redis is running
function is_redis_running() {
redis_status=$(systemctl is-active redis.service 2>&1)
if [ “$redis_status” = “active” ]; then
return 0
else
return 1
fi
}

# Function to check if Redis is accepting operations
function is_redis_accepting_ops() {
if redis-cli set testkey 1 >/dev/null 2>&1 && [ “$(redis-cli get testkey)” = “1” ]; then
redis-cli del testkey >/dev/null 2>&1
return 0
else
return 1
fi
}

# Function to restart Redis
function restart_redis() {
sudo systemctl restart redis.service
}

# Main script
function main() {
if is_redis_running && is_redis_accepting_ops; then
echo “Redis is running and accepting operations.”
else
log_message “Redis is not running or not accepting operations. Restarting Redis…”
restart_redis

# Wait for Redis to start up (you may adjust the sleep time if needed)
sleep 5

if is_redis_running && is_redis_accepting_ops; then
log_message “Redis restarted successfully and is now accepting operations.”
else
log_message “Failed to restart Redis or Redis is still not accepting operations.”
fi
fi
}

#Run
while true
do
main
sleep 10
done

Pin It on Pinterest