#!/bin/bash 2 3# 配置 4SERVICE_NAME="MyApp" 5URL="http://localhost:8080/health" 6MAX_RETRIES=2 7TIMEOUT=5 8LOG_FILE="/var/log/${SERVICE_NAME}_health.log" 9 10# 日志函数 11log() { 12 echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE" 13} 14 15# 健康检查函数 16check_service() { 17 if command -v curl >/dev/null; then 18 curl -sf --max-time "$TIMEOUT" "$URL" > /dev/null 2>&1 19 return $? 20 elif command -v wget >/dev/null; then 21 wget --quiet --timeout="$TIMEOUT" --spider "$URL" > /dev/null 2>&1 22 return $? 23 else 24 log "ERROR: Neither curl nor wget available!" 25 return 1 26 fi 27} 28 29# 主逻辑:带重试 30for ((i=0; i<=MAX_RETRIES; i++)); do 31 if check_service; then 32 log "SUCCESS: $SERVICE_NAME is healthy" 33 exit 0 34 else 35 if [ $i -lt $MAX_RETRIES ]; then 36 log "WARNING: $SERVICE_NAME check failed, retrying in 2s... (attempt $((i+1)))" 37 sleep 2 38 fi 39 fi 40done 41 42# 最终失败 43log "CRITICAL: $SERVICE_NAME is DOWN after $((MAX_RETRIES+1)) attempts" 44exit 1