1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
|
@Service @Slf4j public class NginxMonitorService { @Value("${nginx.status.url}") private String nginxStatusUrl; @Autowired private RestTemplate restTemplate;
@Scheduled(fixedRate = 30000) public void monitorNginxStatus() { try { String statusResponse = restTemplate.getForObject(nginxStatusUrl, String.class); NginxStatus status = parseNginxStatus(statusResponse); log.info("Nginx状态: 活动连接={}, 接受={}, 处理={}, 请求={}", status.getActiveConnections(), status.getAccepts(), status.getHandled(), status.getRequests()); recordMetrics("nginx.connections.active", status.getActiveConnections()); recordMetrics("nginx.connections.accepts", status.getAccepts()); recordMetrics("nginx.connections.handled", status.getHandled()); recordMetrics("nginx.requests.total", status.getRequests()); recordMetrics("nginx.connections.reading", status.getReading()); recordMetrics("nginx.connections.writing", status.getWriting()); recordMetrics("nginx.connections.waiting", status.getWaiting()); checkNginxHealth(status); } catch (Exception e) { log.error("监控Nginx状态失败", e); sendAlert("Nginx监控失败", "critical"); } }
private NginxStatus parseNginxStatus(String response) { NginxStatus status = new NginxStatus(); String[] lines = response.split("\n"); if (lines.length > 0) { String activeConn = lines[0].replaceAll("Active connections: ", "").trim(); status.setActiveConnections(Long.parseLong(activeConn)); } if (lines.length > 2) { String[] stats = lines[2].trim().split("\\s+"); if (stats.length >= 3) { status.setAccepts(Long.parseLong(stats[0])); status.setHandled(Long.parseLong(stats[1])); status.setRequests(Long.parseLong(stats[2])); } } if (lines.length > 3) { String line = lines[3]; status.setReading(extractNumber(line, "Reading:")); status.setWriting(extractNumber(line, "Writing:")); status.setWaiting(extractNumber(line, "Waiting:")); } return status; }
private long extractNumber(String text, String prefix) { int start = text.indexOf(prefix); if (start == -1) return 0; start += prefix.length(); int end = text.indexOf(" ", start); if (end == -1) end = text.length(); String number = text.substring(start, end).trim(); return Long.parseLong(number); }
private void checkNginxHealth(NginxStatus status) { if (status.getAccepts() > 0 && status.getHandled() > 0) { double handleRate = (double) status.getHandled() / status.getAccepts(); if (handleRate < 0.95) { log.warn("Nginx连接处理率过低: {}%", handleRate * 100); sendAlert("Nginx连接处理率过低", "warning"); } } if (status.getActiveConnections() > 10000) { log.warn("Nginx活动连接数过多: {}", status.getActiveConnections()); sendAlert("Nginx活动连接数过多", "warning"); } if (status.getWaiting() > 1000) { log.warn("Nginx等待连接数过多: {}", status.getWaiting()); sendAlert("Nginx等待连接数过多", "warning"); } }
@Scheduled(fixedRate = 60000) public void monitorNginxLogs() { try { analyzeAccessLog(); analyzeErrorLog(); } catch (Exception e) { log.error("监控Nginx日志失败", e); } }
private void analyzeAccessLog() { try { String logFile = "/var/log/nginx/access.log"; LocalDateTime oneMinuteAgo = LocalDateTime.now().minusMinutes(1); Map<Integer, Long> statusCodes = new HashMap<>(); long totalRequests = 0; double totalResponseTime = 0; try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { String line; while ((line = reader.readLine()) != null) { AccessLogEntry entry = parseAccessLogEntry(line); if (entry != null && entry.getTimestamp().isAfter(oneMinuteAgo)) { totalRequests++; totalResponseTime += entry.getResponseTime(); statusCodes.merge(entry.getStatusCode(), 1L, Long::sum); } } } if (totalRequests > 0) { double avgResponseTime = totalResponseTime / totalRequests; recordMetrics("nginx.requests.rate", totalRequests); recordMetrics("nginx.response.time.avg", avgResponseTime); statusCodes.forEach((code, count) -> { recordMetrics("nginx.status." + code, count); }); long errorCount = statusCodes.entrySet().stream() .filter(e -> e.getKey() >= 500) .mapToLong(Map.Entry::getValue) .sum(); double errorRate = (double) errorCount / totalRequests; if (errorRate > 0.05) { log.error("Nginx错误率过高: {}%", errorRate * 100); sendAlert("Nginx错误率过高", "critical"); } } } catch (Exception e) { log.error("分析访问日志失败", e); } }
private AccessLogEntry parseAccessLogEntry(String line) { return null; }
private void analyzeErrorLog() { try { String logFile = "/var/log/nginx/error.log"; LocalDateTime oneMinuteAgo = LocalDateTime.now().minusMinutes(1); List<String> criticalErrors = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { String line; while ((line = reader.readLine()) != null) { if (line.contains("[crit]") || line.contains("[alert]") || line.contains("[emerg]")) { criticalErrors.add(line); } } } if (!criticalErrors.isEmpty()) { log.error("发现Nginx严重错误,共{}条", criticalErrors.size()); sendAlert("Nginx严重错误: " + criticalErrors.size() + "条", "critical"); } } catch (Exception e) { log.error("分析错误日志失败", e); } }
private void recordMetrics(String metricName, Number value) { log.debug("记录指标: {}={}", metricName, value); }
private void sendAlert(String message, String level) { log.info("发送告警: message={}, level={}", message, level); } }
|