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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
|
@Service public class NettyMonitorService {
@Autowired private NettyConnectionMonitorMapper nettyConnectionMonitorMapper; @Autowired private NettyPerformanceMonitorMapper nettyPerformanceMonitorMapper; @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private AlertService alertService; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private ServerBootstrap serverBootstrap; private Channel serverChannel; private AtomicLong totalBytesReceived = new AtomicLong(0); private AtomicLong totalBytesSent = new AtomicLong(0); private AtomicLong totalMessagesReceived = new AtomicLong(0); private AtomicLong totalMessagesSent = new AtomicLong(0); private AtomicInteger activeConnections = new AtomicInteger(0); private AtomicInteger totalConnections = new AtomicInteger(0);
@PostConstruct public void startNettyServer() { try { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(8); serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("monitor", new NettyMonitorHandler()); pipeline.addLast("handler", new NettyBusinessHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); serverChannel = serverBootstrap.bind(9999).sync().channel(); log.info("Netty服务器启动成功,端口: 9999"); } catch (Exception e) { log.error("启动Netty服务器失败: {}", e.getMessage(), e); } }
@Scheduled(fixedRate = 5000) public void collectNettyData() { try { collectConnectionInfo(); collectPerformanceInfo(); } catch (Exception e) { log.error("采集Netty数据失败: {}", e.getMessage(), e); } }
private void collectConnectionInfo() { try { NettyConnectionInfo connectionInfo = getConnectionInfo(); NettyConnectionMonitor monitorData = createConnectionMonitorData(connectionInfo); nettyConnectionMonitorMapper.insert(monitorData); updateConnectionCache(monitorData); checkConnectionAlert(monitorData); log.debug("采集连接信息: activeConnections={}, totalConnections={}", monitorData.getActiveConnections(), monitorData.getTotalConnections()); } catch (Exception e) { log.error("采集连接信息失败: {}", e.getMessage(), e); } }
private NettyConnectionInfo getConnectionInfo() { NettyConnectionInfo connectionInfo = new NettyConnectionInfo(); try { connectionInfo.setTotalConnections(totalConnections.get()); connectionInfo.setActiveConnections(activeConnections.get()); connectionInfo.setInactiveConnections(totalConnections.get() - activeConnections.get()); connectionInfo.setTotalBytesReceived(totalBytesReceived.get()); connectionInfo.setTotalBytesSent(totalBytesSent.get()); connectionInfo.setTotalMessagesReceived(totalMessagesReceived.get()); connectionInfo.setTotalMessagesSent(totalMessagesSent.get()); connectionInfo.setAvgResponseTime(calculateAvgResponseTime()); connectionInfo.setMaxResponseTime(calculateMaxResponseTime()); MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); connectionInfo.setMemoryUsed(heapUsage.getUsed()); connectionInfo.setMemoryMax(heapUsage.getMax()); connectionInfo.setMemoryUsage((double) heapUsage.getUsed() / heapUsage.getMax() * 100); connectionInfo.setEventLoopThreads(workerGroup.executorCount()); connectionInfo.setActiveEventLoops(workerGroup.executorCount()); connectionInfo.setNettyStatus(serverChannel != null && serverChannel.isActive() ? "Running" : "Stopped"); } catch (Exception e) { log.error("获取连接信息失败: {}", e.getMessage(), e); } return connectionInfo; }
private double calculateAvgResponseTime() { return 10.0; }
private double calculateMaxResponseTime() { return 100.0; }
private NettyConnectionMonitor createConnectionMonitorData(NettyConnectionInfo connectionInfo) { NettyConnectionMonitor monitorData = new NettyConnectionMonitor(); monitorData.setHostname(getHostname()); monitorData.setIp(getLocalIpAddress()); monitorData.setServerName("netty-server"); monitorData.setCollectTime(new Date()); monitorData.setCreateTime(new Date()); monitorData.setTotalConnections(connectionInfo.getTotalConnections()); monitorData.setActiveConnections(connectionInfo.getActiveConnections()); monitorData.setInactiveConnections(connectionInfo.getInactiveConnections()); monitorData.setTotalBytesReceived(connectionInfo.getTotalBytesReceived()); monitorData.setTotalBytesSent(connectionInfo.getTotalBytesSent()); monitorData.setTotalMessagesReceived(connectionInfo.getTotalMessagesReceived()); monitorData.setTotalMessagesSent(connectionInfo.getTotalMessagesSent()); monitorData.setAvgResponseTime(connectionInfo.getAvgResponseTime()); monitorData.setMaxResponseTime(connectionInfo.getMaxResponseTime()); monitorData.setMemoryUsed(connectionInfo.getMemoryUsed()); monitorData.setMemoryMax(connectionInfo.getMemoryMax()); monitorData.setMemoryUsage(connectionInfo.getMemoryUsage()); monitorData.setEventLoopThreads(connectionInfo.getEventLoopThreads()); monitorData.setActiveEventLoops(connectionInfo.getActiveEventLoops()); monitorData.setNettyStatus(connectionInfo.getNettyStatus()); return monitorData; }
private void collectPerformanceInfo() { try { NettyPerformanceInfo performanceInfo = getPerformanceInfo(); NettyPerformanceMonitor monitorData = createPerformanceMonitorData(performanceInfo); nettyPerformanceMonitorMapper.insert(monitorData); updatePerformanceCache(monitorData); checkPerformanceAlert(monitorData); log.debug("采集性能信息: throughput={}, latency={}ms", monitorData.getThroughput(), monitorData.getLatency()); } catch (Exception e) { log.error("采集性能信息失败: {}", e.getMessage(), e); } }
private NettyPerformanceInfo getPerformanceInfo() { NettyPerformanceInfo performanceInfo = new NettyPerformanceInfo(); try { performanceInfo.setThroughput(calculateThroughput()); performanceInfo.setLatency(calculateLatency()); performanceInfo.setChannelCount(activeConnections.get()); performanceInfo.setPendingTasks(calculatePendingTasks()); performanceInfo.setCompletedTasks(calculateCompletedTasks()); performanceInfo.setTaskCompletionRate(calculateTaskCompletionRate()); MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); performanceInfo.setDirectMemoryUsed(calculateDirectMemoryUsed()); performanceInfo.setHeapMemoryUsed(heapUsage.getUsed()); performanceInfo.setCpuUsage(calculateCpuUsage()); performanceInfo.setPerformanceStatus(determinePerformanceStatus(performanceInfo)); } catch (Exception e) { log.error("获取性能信息失败: {}", e.getMessage(), e); } return performanceInfo; }
private double calculateThroughput() { return totalMessagesReceived.get() / 5.0; }
private double calculateLatency() { return 10.0; }
private long calculatePendingTasks() { return 0; }
private long calculateCompletedTasks() { return totalMessagesReceived.get(); }
private double calculateTaskCompletionRate() { long completed = calculateCompletedTasks(); long pending = calculatePendingTasks(); long total = completed + pending; return total > 0 ? (double) completed / total * 100 : 100.0; }
private long calculateDirectMemoryUsed() { try { MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); MemoryUsage nonHeapUsage = memoryBean.getNonHeapMemoryUsage(); return nonHeapUsage.getUsed(); } catch (Exception e) { return 0; } }
private double calculateCpuUsage() { try { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getProcessCpuLoad() * 100; } catch (Exception e) { return 0.0; } }
private String determinePerformanceStatus(NettyPerformanceInfo performanceInfo) { String status = "Normal"; if (performanceInfo.getThroughput() < 100) { status = "Low Throughput"; } else if (performanceInfo.getLatency() > 100) { status = "High Latency"; } else if (performanceInfo.getCpuUsage() > 80) { status = "High CPU Usage"; } return status; }
private NettyPerformanceMonitor createPerformanceMonitorData(NettyPerformanceInfo performanceInfo) { NettyPerformanceMonitor monitorData = new NettyPerformanceMonitor(); monitorData.setHostname(getHostname()); monitorData.setServerName("netty-server"); monitorData.setCollectTime(new Date()); monitorData.setCreateTime(new Date()); monitorData.setThroughput(performanceInfo.getThroughput()); monitorData.setLatency(performanceInfo.getLatency()); monitorData.setChannelCount(performanceInfo.getChannelCount()); monitorData.setPendingTasks(performanceInfo.getPendingTasks()); monitorData.setCompletedTasks(performanceInfo.getCompletedTasks()); monitorData.setTaskCompletionRate(performanceInfo.getTaskCompletionRate()); monitorData.setDirectMemoryUsed(performanceInfo.getDirectMemoryUsed()); monitorData.setHeapMemoryUsed(performanceInfo.getHeapMemoryUsed()); monitorData.setCpuUsage(performanceInfo.getCpuUsage()); monitorData.setPerformanceStatus(performanceInfo.getPerformanceStatus()); return monitorData; }
private void updateConnectionCache(NettyConnectionMonitor monitorData) { try { String cacheKey = "netty:connection:realtime"; redisTemplate.opsForValue().set(cacheKey, monitorData, Duration.ofMinutes(5)); } catch (Exception e) { log.warn("更新连接缓存失败: {}", e.getMessage()); } }
private void updatePerformanceCache(NettyPerformanceMonitor monitorData) { try { String cacheKey = "netty:performance:realtime"; redisTemplate.opsForValue().set(cacheKey, monitorData, Duration.ofMinutes(5)); } catch (Exception e) { log.warn("更新性能缓存失败: {}", e.getMessage()); } }
private void checkConnectionAlert(NettyConnectionMonitor monitorData) { try { String alertType = null; String alertLevel = null; String alertMessage = null; if (monitorData.getActiveConnections() > 9000) { alertType = "NETTY_CONNECTIONS_HIGH"; alertLevel = "CRITICAL"; alertMessage = String.format("Netty连接数过高: %d", monitorData.getActiveConnections()); } else if (monitorData.getActiveConnections() > 8000) { alertType = "NETTY_CONNECTIONS_WARNING"; alertLevel = "WARNING"; alertMessage = String.format("Netty连接数较高: %d", monitorData.getActiveConnections()); } if (monitorData.getMemoryUsage() > 90) { alertType = "NETTY_MEMORY_HIGH"; alertLevel = "CRITICAL"; alertMessage = String.format("Netty内存使用率过高: %.2f%%", monitorData.getMemoryUsage()); } else if (monitorData.getMemoryUsage() > 80) { alertType = "NETTY_MEMORY_WARNING"; alertLevel = "WARNING"; alertMessage = String.format("Netty内存使用率较高: %.2f%%", monitorData.getMemoryUsage()); } if (alertType != null) { sendConnectionAlert(monitorData, alertType, alertLevel, alertMessage); } } catch (Exception e) { log.error("检查连接告警失败: {}", e.getMessage(), e); } }
private void checkPerformanceAlert(NettyPerformanceMonitor monitorData) { try { String alertType = null; String alertLevel = null; String alertMessage = null; if (monitorData.getThroughput() < 100) { alertType = "NETTY_THROUGHPUT_LOW"; alertLevel = "WARNING"; alertMessage = String.format("Netty吞吐量过低: %.2f", monitorData.getThroughput()); } if (monitorData.getLatency() > 200) { alertType = "NETTY_LATENCY_HIGH"; alertLevel = "WARNING"; alertMessage = String.format("Netty延迟过高: %.2fms", monitorData.getLatency()); } if (monitorData.getCpuUsage() > 90) { alertType = "NETTY_CPU_HIGH"; alertLevel = "CRITICAL"; alertMessage = String.format("Netty CPU使用率过高: %.2f%%", monitorData.getCpuUsage()); } if (alertType != null) { sendPerformanceAlert(monitorData, alertType, alertLevel, alertMessage); } } catch (Exception e) { log.error("检查性能告警失败: {}", e.getMessage(), e); } }
private void sendConnectionAlert(NettyConnectionMonitor monitorData, String alertType, String alertLevel, String alertMessage) { try { String alertKey = "netty:connection:alert:" + alertType; Boolean hasAlert = redisTemplate.hasKey(alertKey); if (hasAlert == null || !hasAlert) { AlertMessage alert = new AlertMessage(); alert.setType(alertType); alert.setLevel(alertLevel); alert.setMessage(alertMessage); alert.setTimestamp(new Date()); alert.setHostname(monitorData.getHostname()); alertService.sendAlert(alert); redisTemplate.opsForValue().set(alertKey, "1", Duration.ofMinutes(5)); log.warn("发送连接告警: type={}, level={}", alertType, alertLevel); } } catch (Exception e) { log.error("发送连接告警失败: {}", e.getMessage(), e); } }
private void sendPerformanceAlert(NettyPerformanceMonitor monitorData, String alertType, String alertLevel, String alertMessage) { try { String alertKey = "netty:performance:alert:" + alertType; Boolean hasAlert = redisTemplate.hasKey(alertKey); if (hasAlert == null || !hasAlert) { AlertMessage alert = new AlertMessage(); alert.setType(alertType); alert.setLevel(alertLevel); alert.setMessage(alertMessage); alert.setTimestamp(new Date()); alert.setHostname(monitorData.getHostname()); alertService.sendAlert(alert); redisTemplate.opsForValue().set(alertKey, "1", Duration.ofMinutes(5)); log.warn("发送性能告警: type={}, level={}", alertType, alertLevel); } } catch (Exception e) { log.error("发送性能告警失败: {}", e.getMessage(), e); } }
public NettyConnectionMonitor getRealTimeConnectionData() { String cacheKey = "netty:connection:realtime"; return (NettyConnectionMonitor) redisTemplate.opsForValue().get(cacheKey); }
public NettyPerformanceMonitor getRealTimePerformanceData() { String cacheKey = "netty:performance:realtime"; return (NettyPerformanceMonitor) redisTemplate.opsForValue().get(cacheKey); }
private String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "unknown"; } }
private String getLocalIpAddress() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { return "127.0.0.1"; } }
@PreDestroy public void shutdownNettyServer() { try { if (serverChannel != null) { serverChannel.close().sync(); } if (workerGroup != null) { workerGroup.shutdownGracefully(); } if (bossGroup != null) { bossGroup.shutdownGracefully(); } log.info("Netty服务器关闭成功"); } catch (Exception e) { log.error("关闭Netty服务器失败: {}", e.getMessage(), e); } } }
@Data public class NettyConnectionInfo { private Integer totalConnections; private Integer activeConnections; private Integer inactiveConnections; private Long totalBytesReceived; private Long totalBytesSent; private Long totalMessagesReceived; private Long totalMessagesSent; private Double avgResponseTime; private Double maxResponseTime; private Long memoryUsed; private Long memoryMax; private Double memoryUsage; private Integer eventLoopThreads; private Integer activeEventLoops; private String nettyStatus; }
@Data public class NettyPerformanceInfo { private Double throughput; private Double latency; private Long channelCount; private Long pendingTasks; private Long completedTasks; private Double taskCompletionRate; private Long directMemoryUsed; private Long heapMemoryUsed; private Double cpuUsage; private String performanceStatus; }
|