functioncheck_server() { local server=$1 local url="http://${server}${HEALTH_CHECK_URL}" # 发送健康检查请求 response=$(curl -s -w "%{http_code}" -o /dev/null --connect-timeout $TIMEOUT"$url") if [ "$response" = "200" ]; then echo"$(date): Server $server is healthy" >> $LOG_FILE return 0 else echo"$(date): Server $server is unhealthy (HTTP $response)" >> $LOG_FILE return 1 fi }
functionupdate_upstream() { local server=$1 local action=$2# "enable" or "disable" # 使用Nginx Plus API更新upstream if [ "$action" = "disable" ]; then curl -X PATCH -d '{"down":true}' \ "http://localhost/api/6/http/upstreams/backend/servers/${server}" else curl -X PATCH -d '{"down":false}' \ "http://localhost/api/6/http/upstreams/backend/servers/${server}" fi }
# 主循环 whiletrue; do for server in"${UPSTREAM_SERVERS[@]}"; do if check_server "$server"; then update_upstream "$server""enable" else update_upstream "$server""disable" fi done sleep 10 done
functioncheck_thresholds() { local active_connections=$1 local waiting_connections=$2 # 检查连接数阈值 if [ "$active_connections" -gt 1000 ]; then echo"$(date): High active connections: $active_connections" >> $LOG_FILE send_alert "High active connections: $active_connections" fi if [ "$waiting_connections" -gt 500 ]; then echo"$(date): High waiting connections: $waiting_connections" >> $LOG_FILE send_alert "High waiting connections: $waiting_connections" fi }
functionsend_alert() { local message=$1 echo"$message" | mail -s "Nginx Load Balancer Alert""$ALERT_EMAIL" }
# 优化CPU亲和性 functionoptimize_cpu_affinity() { local process_name=$1 local cpu_cores=$2 echo"优化 $process_name 的CPU亲和性..." # 查找进程PID local pids=$(pgrep $process_name) for pid in$pids; do if [ -n "$pid" ]; then taskset -cp$cpu_cores$pid echo"进程 $pid 绑定到CPU核心 $cpu_cores" fi done }
# 设置进程优先级 functionset_process_priority() { local process_name=$1 local nice_value=$2 echo"设置 $process_name 进程优先级为 $nice_value" local pids=$(pgrep $process_name) for pid in$pids; do if [ -n "$pid" ]; then renice $nice_value$pid fi done }