1. MongoDB数据库运维监控概述

MongoDB作为流行的NoSQL文档数据库,在生产环境中需要专业的运维监控和管理。本文将详细介绍MongoDB集群监控、副本集管理、分片优化、性能调优的完整解决方案,帮助运维人员有效管理MongoDB集群。

1.1 核心挑战

  1. 集群监控: 实时监控MongoDB集群和节点状态
  2. 副本集管理: 管理副本集和故障切换
  3. 分片优化: 优化分片策略和数据分布
  4. 性能调优: 优化MongoDB性能和查询效率
  5. 故障诊断: 快速定位MongoDB相关问题

1.2 技术架构

1
2
3
4
5
MongoDB监控 → 数据采集 → 性能分析 → 告警通知 → 自动优化
↓ ↓ ↓ ↓ ↓
集群指标 → 监控代理 → 数据存储 → 告警引擎 → 调优脚本
↓ ↓ ↓ ↓ ↓
副本集管理 → 分片优化 → 性能调优 → 自动修复 → 运维记录

2. MongoDB监控系统

2.1 Maven依赖配置

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
<!-- pom.xml -->
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Boot Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- MongoDB Driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.9.1</version>
</dependency>

<!-- Micrometer监控 -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
</dependencies>

2.2 应用配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# application.yml
server:
port: 8080

spring:
redis:
host: localhost
port: 6379
database: 0

# MongoDB监控配置
mongodb-monitor:
connection-string: "mongodb://localhost:27017" # MongoDB连接字符串
cluster-name: "production-cluster" # 集群名称
collection-interval: 10000 # 采集间隔(毫秒)
query-timeout: 30000 # 查询超时时间(毫秒)
replica-set-threshold: 80 # 副本集告警阈值(%)
shard-threshold: 90 # 分片告警阈值(%)

3. MongoDB监控服务

3.1 MongoDB监控实体类

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
/**
* MongoDB集群监控数据实体类
*/
@Data
@TableName("mongodb_cluster_monitor")
public class MongoDBClusterMonitor {

@TableId(type = IdType.AUTO)
private Long id; // 主键ID

private String clusterName; // 集群名称

private String hostname; // 主机名

private String ip; // IP地址

private Integer nodeCount; // 节点数量

private Integer databaseCount; // 数据库数量

private Integer collectionCount; // 集合数量

private Long totalDocuments; // 总文档数

private Long totalSize; // 总大小(字节)

private String clusterStatus; // 集群状态

private String replicaSetStatus; // 副本集状态

private Integer primaryNodes; // 主节点数量

private Integer secondaryNodes; // 从节点数量

private Integer arbiterNodes; // 仲裁节点数量

private Long operationsPerSecond; // 每秒操作数

private Long queriesPerSecond; // 每秒查询数

private Long insertsPerSecond; // 每秒插入数

private Long updatesPerSecond; // 每秒更新数

private Long deletesPerSecond; // 每秒删除数

private Double avgQueryTime; // 平均查询时间(毫秒)

private Long connections; // 连接数

private Long maxConnections; // 最大连接数

private Double connectionUsage; // 连接使用率

private Long memoryUsed; // 内存使用量(字节)

private Long memoryTotal; // 总内存(字节)

private Double memoryUsage; // 内存使用率

private Long diskUsed; // 磁盘使用量(字节)

private Long diskTotal; // 总磁盘空间(字节)

private Double diskUsage; // 磁盘使用率

private Date collectTime; // 采集时间

private Date createTime; // 创建时间
}

/**
* MongoDB副本集监控数据实体类
*/
@Data
@TableName("mongodb_replicaset_monitor")
public class MongoDBReplicaSetMonitor {

@TableId(type = IdType.AUTO)
private Long id; // 主键ID

private String clusterName; // 集群名称

private String replicaSetName; // 副本集名称

private String nodeName; // 节点名称

private String nodeRole; // 节点角色(primary/secondary/arbiter)

private String nodeStatus; // 节点状态

private String nodeState; // 节点状态

private Long uptime; // 运行时间(秒)

private Long oplogSize; // 操作日志大小(字节)

private Long oplogUsed; // 操作日志已使用(字节)

private Double oplogUsage; // 操作日志使用率

private Long replicationLag; // 复制延迟(毫秒)

private Long lastHeartbeat; // 最后心跳时间

private String nodeHealth; // 节点健康状态

private Date collectTime; // 采集时间

private Date createTime; // 创建时间
}

3.2 MongoDB监控服务

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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
/**
* MongoDB监控服务
* 负责MongoDB集群和副本集数据的采集、存储和分析
*/
@Service
public class MongoDBMonitorService {

@Autowired
private MongoDBClusterMonitorMapper mongodbClusterMonitorMapper;

@Autowired
private MongoDBReplicaSetMonitorMapper mongodbReplicaSetMonitorMapper;

@Autowired
private RedisTemplate<String, Object> redisTemplate;

@Autowired
private AlertService alertService;

private MongoClient mongoClient;
private MongoDatabase adminDatabase;

/**
* 初始化MongoDB客户端
*/
@PostConstruct
public void initMongoDBClient() {
try {
// 创建MongoDB客户端
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("mongodb://localhost:27017"))
.build();

mongoClient = MongoClients.create(settings);
adminDatabase = mongoClient.getDatabase("admin");

log.info("MongoDB客户端初始化成功");

} catch (Exception e) {
log.error("初始化MongoDB客户端失败: {}", e.getMessage(), e);
}
}

/**
* 采集MongoDB集群数据
* 定期采集MongoDB集群和副本集信息
*/
@Scheduled(fixedRate = 10000) // 每10秒执行一次
public void collectMongoDBData() {
try {
// 1. 采集集群信息
collectClusterInfo();

// 2. 采集副本集信息
collectReplicaSetInfo();

} catch (Exception e) {
log.error("采集MongoDB数据失败: {}", e.getMessage(), e);
}
}

/**
* 采集集群信息
*/
private void collectClusterInfo() {
try {
// 1. 获取集群信息
MongoDBClusterInfo clusterInfo = getClusterInfo();

// 2. 创建集群监控数据
MongoDBClusterMonitor monitorData = createClusterMonitorData(clusterInfo);

// 3. 保存到数据库
mongodbClusterMonitorMapper.insert(monitorData);

// 4. 更新缓存
updateClusterCache(monitorData);

// 5. 检查集群告警
checkClusterAlert(monitorData);

log.debug("采集集群信息: nodeCount={}, databaseCount={}",
monitorData.getNodeCount(), monitorData.getDatabaseCount());

} catch (Exception e) {
log.error("采集集群信息失败: {}", e.getMessage(), e);
}
}

/**
* 获取集群信息
*/
private MongoDBClusterInfo getClusterInfo() {
MongoDBClusterInfo clusterInfo = new MongoDBClusterInfo();

try {
// 获取服务器状态
setServerStatus(clusterInfo);

// 获取数据库和集合信息
setDatabaseAndCollectionInfo(clusterInfo);

// 获取副本集信息
setReplicaSetInfo(clusterInfo);

// 获取性能统计信息
setPerformanceStatistics(clusterInfo);

// 获取资源使用信息
setResourceUsageInfo(clusterInfo);

} catch (Exception e) {
log.error("获取集群信息失败: {}", e.getMessage(), e);
}

return clusterInfo;
}

/**
* 设置服务器状态
*/
private void setServerStatus(MongoDBClusterInfo clusterInfo) {
try {
// 获取服务器状态
Document serverStatus = adminDatabase.runCommand(new Document("serverStatus", 1));

clusterInfo.setClusterName(serverStatus.getString("repl", "standalone"));
clusterInfo.setClusterStatus("running");

// 获取连接信息
Document connections = serverStatus.get("connections", Document.class);
if (connections != null) {
clusterInfo.setConnections(connections.getLong("current"));
clusterInfo.setMaxConnections(connections.getLong("available"));
clusterInfo.setConnectionUsage((double) connections.getLong("current") /
connections.getLong("available") * 100);
}

// 获取操作统计
Document opcounters = serverStatus.get("opcounters", Document.class);
if (opcounters != null) {
clusterInfo.setQueriesPerSecond(opcounters.getLong("query"));
clusterInfo.setInsertsPerSecond(opcounters.getLong("insert"));
clusterInfo.setUpdatesPerSecond(opcounters.getLong("update"));
clusterInfo.setDeletesPerSecond(opcounters.getLong("delete"));
}

} catch (Exception e) {
log.error("设置服务器状态失败: {}", e.getMessage(), e);
}
}

/**
* 设置数据库和集合信息
*/
private void setDatabaseAndCollectionInfo(MongoDBClusterInfo clusterInfo) {
try {
// 获取数据库列表
List<String> databaseNames = mongoClient.listDatabaseNames().into(new ArrayList<>());
clusterInfo.setDatabaseCount(databaseNames.size());

int totalCollections = 0;
long totalDocuments = 0;
long totalSize = 0;

for (String dbName : databaseNames) {
if (!dbName.equals("admin") && !dbName.equals("local") && !dbName.equals("config")) {
MongoDatabase database = mongoClient.getDatabase(dbName);

// 获取集合列表
List<String> collectionNames = database.listCollectionNames().into(new ArrayList<>());
totalCollections += collectionNames.size();

// 获取集合统计信息
for (String collectionName : collectionNames) {
MongoCollection<Document> collection = database.getCollection(collectionName);

// 获取文档数量
long documentCount = collection.countDocuments();
totalDocuments += documentCount;

// 获取集合大小
Document stats = database.runCommand(new Document("collStats", collectionName));
if (stats.containsKey("size")) {
totalSize += stats.getLong("size");
}
}
}
}

clusterInfo.setCollectionCount(totalCollections);
clusterInfo.setTotalDocuments(totalDocuments);
clusterInfo.setTotalSize(totalSize);

} catch (Exception e) {
log.error("设置数据库和集合信息失败: {}", e.getMessage(), e);
}
}

/**
* 设置副本集信息
*/
private void setReplicaSetInfo(MongoDBClusterInfo clusterInfo) {
try {
// 获取副本集状态
Document replSetStatus = adminDatabase.runCommand(new Document("replSetGetStatus", 1));

if (replSetStatus.containsKey("members")) {
List<Document> members = (List<Document>) replSetStatus.get("members");
clusterInfo.setNodeCount(members.size());

int primaryCount = 0;
int secondaryCount = 0;
int arbiterCount = 0;

for (Document member : members) {
String stateStr = member.getString("stateStr");
switch (stateStr) {
case "PRIMARY":
primaryCount++;
break;
case "SECONDARY":
secondaryCount++;
break;
case "ARBITER":
arbiterCount++;
break;
}
}

clusterInfo.setPrimaryNodes(primaryCount);
clusterInfo.setSecondaryNodes(secondaryCount);
clusterInfo.setArbiterNodes(arbiterCount);

clusterInfo.setReplicaSetStatus(replSetStatus.getString("ok") == "1" ? "healthy" : "unhealthy");
} else {
clusterInfo.setNodeCount(1);
clusterInfo.setPrimaryNodes(1);
clusterInfo.setSecondaryNodes(0);
clusterInfo.setArbiterNodes(0);
clusterInfo.setReplicaSetStatus("standalone");
}

} catch (Exception e) {
log.error("设置副本集信息失败: {}", e.getMessage(), e);
}
}

/**
* 设置性能统计信息
*/
private void setPerformanceStatistics(MongoDBClusterInfo clusterInfo) {
try {
// 获取操作统计
Document serverStatus = adminDatabase.runCommand(new Document("serverStatus", 1));

Document opcounters = serverStatus.get("opcounters", Document.class);
if (opcounters != null) {
clusterInfo.setOperationsPerSecond(opcounters.getLong("query") +
opcounters.getLong("insert") + opcounters.getLong("update") +
opcounters.getLong("delete"));
}

// 计算平均查询时间
Document metrics = serverStatus.get("metrics", Document.class);
if (metrics != null) {
Document query = metrics.get("query", Document.class);
if (query != null) {
long queryCount = query.getLong("executor", 0L);
long queryTime = query.getLong("executorTime", 0L);
if (queryCount > 0) {
clusterInfo.setAvgQueryTime((double) queryTime / queryCount);
}
}
}

} catch (Exception e) {
log.error("设置性能统计信息失败: {}", e.getMessage(), e);
}
}

/**
* 设置资源使用信息
*/
private void setResourceUsageInfo(MongoDBClusterInfo clusterInfo) {
try {
// 获取服务器状态
Document serverStatus = adminDatabase.runCommand(new Document("serverStatus", 1));

// 获取内存信息
Document mem = serverStatus.get("mem", Document.class);
if (mem != null) {
clusterInfo.setMemoryUsed(mem.getLong("resident") * 1024 * 1024); // 转换为字节
clusterInfo.setMemoryTotal(mem.getLong("virtual") * 1024 * 1024); // 转换为字节
clusterInfo.setMemoryUsage((double) mem.getLong("resident") / mem.getLong("virtual") * 100);
}

// 获取磁盘信息
Document storageEngine = serverStatus.get("storageEngine", Document.class);
if (storageEngine != null) {
// 简化处理,实际应该从系统信息获取
clusterInfo.setDiskUsed(0L);
clusterInfo.setDiskTotal(0L);
clusterInfo.setDiskUsage(0.0);
}

} catch (Exception e) {
log.error("设置资源使用信息失败: {}", e.getMessage(), e);
}
}

/**
* 创建集群监控数据
*/
private MongoDBClusterMonitor createClusterMonitorData(MongoDBClusterInfo clusterInfo) {
MongoDBClusterMonitor monitorData = new MongoDBClusterMonitor();

// 设置基本信息
monitorData.setClusterName(clusterInfo.getClusterName());
monitorData.setHostname(getHostname());
monitorData.setIp(getLocalIpAddress());
monitorData.setCollectTime(new Date());
monitorData.setCreateTime(new Date());

// 设置集群信息
monitorData.setNodeCount(clusterInfo.getNodeCount());
monitorData.setDatabaseCount(clusterInfo.getDatabaseCount());
monitorData.setCollectionCount(clusterInfo.getCollectionCount());

// 设置数据信息
monitorData.setTotalDocuments(clusterInfo.getTotalDocuments());
monitorData.setTotalSize(clusterInfo.getTotalSize());

// 设置状态信息
monitorData.setClusterStatus(clusterInfo.getClusterStatus());
monitorData.setReplicaSetStatus(clusterInfo.getReplicaSetStatus());
monitorData.setPrimaryNodes(clusterInfo.getPrimaryNodes());
monitorData.setSecondaryNodes(clusterInfo.getSecondaryNodes());
monitorData.setArbiterNodes(clusterInfo.getArbiterNodes());

// 设置性能信息
monitorData.setOperationsPerSecond(clusterInfo.getOperationsPerSecond());
monitorData.setQueriesPerSecond(clusterInfo.getQueriesPerSecond());
monitorData.setInsertsPerSecond(clusterInfo.getInsertsPerSecond());
monitorData.setUpdatesPerSecond(clusterInfo.getUpdatesPerSecond());
monitorData.setDeletesPerSecond(clusterInfo.getDeletesPerSecond());
monitorData.setAvgQueryTime(clusterInfo.getAvgQueryTime());

// 设置连接信息
monitorData.setConnections(clusterInfo.getConnections());
monitorData.setMaxConnections(clusterInfo.getMaxConnections());
monitorData.setConnectionUsage(clusterInfo.getConnectionUsage());

// 设置资源信息
monitorData.setMemoryUsed(clusterInfo.getMemoryUsed());
monitorData.setMemoryTotal(clusterInfo.getMemoryTotal());
monitorData.setMemoryUsage(clusterInfo.getMemoryUsage());
monitorData.setDiskUsed(clusterInfo.getDiskUsed());
monitorData.setDiskTotal(clusterInfo.getDiskTotal());
monitorData.setDiskUsage(clusterInfo.getDiskUsage());

return monitorData;
}

/**
* 采集副本集信息
*/
private void collectReplicaSetInfo() {
try {
// 获取副本集状态
Document replSetStatus = adminDatabase.runCommand(new Document("replSetGetStatus", 1));

if (replSetStatus.containsKey("members")) {
List<Document> members = (List<Document>) replSetStatus.get("members");

for (Document member : members) {
try {
// 创建副本集监控数据
MongoDBReplicaSetMonitor replicaSetMonitor = createReplicaSetMonitorData(member);

// 保存到数据库
mongodbReplicaSetMonitorMapper.insert(replicaSetMonitor);

// 更新缓存
updateReplicaSetCache(replicaSetMonitor);

// 检查副本集告警
checkReplicaSetAlert(replicaSetMonitor);

} catch (Exception e) {
log.error("处理副本集成员失败: member={}, error={}",
member.getString("name"), e.getMessage());
}
}
}

} catch (Exception e) {
log.error("采集副本集信息失败: {}", e.getMessage(), e);
}
}

/**
* 创建副本集监控数据
*/
private MongoDBReplicaSetMonitor createReplicaSetMonitorData(Document member) {
MongoDBReplicaSetMonitor replicaSetMonitor = new MongoDBReplicaSetMonitor();

// 设置基本信息
replicaSetMonitor.setClusterName("production-cluster");
replicaSetMonitor.setReplicaSetName("rs0");
replicaSetMonitor.setNodeName(member.getString("name"));
replicaSetMonitor.setCollectTime(new Date());
replicaSetMonitor.setCreateTime(new Date());

// 设置节点信息
replicaSetMonitor.setNodeRole(member.getString("stateStr"));
replicaSetMonitor.setNodeStatus(member.getString("stateStr"));
replicaSetMonitor.setNodeState(member.getString("stateStr"));

// 设置运行时间
replicaSetMonitor.setUptime(member.getLong("uptime"));

// 设置操作日志信息
if (member.containsKey("optimeDate")) {
replicaSetMonitor.setLastHeartbeat(member.getDate("optimeDate").getTime());
}

// 设置复制延迟
if (member.containsKey("lag")) {
replicaSetMonitor.setReplicationLag(member.getLong("lag"));
}

// 设置健康状态
replicaSetMonitor.setNodeHealth("healthy");

return replicaSetMonitor;
}

/**
* 更新集群缓存
*/
private void updateClusterCache(MongoDBClusterMonitor monitorData) {
try {
String cacheKey = "mongodb:cluster:" + monitorData.getClusterName();
redisTemplate.opsForValue().set(cacheKey, monitorData, Duration.ofMinutes(5));

} catch (Exception e) {
log.warn("更新集群缓存失败: {}", e.getMessage());
}
}

/**
* 更新副本集缓存
*/
private void updateReplicaSetCache(MongoDBReplicaSetMonitor replicaSetMonitor) {
try {
String cacheKey = "mongodb:replicaset:" + replicaSetMonitor.getNodeName();
redisTemplate.opsForValue().set(cacheKey, replicaSetMonitor, Duration.ofMinutes(5));

} catch (Exception e) {
log.warn("更新副本集缓存失败: {}", e.getMessage());
}
}

/**
* 检查集群告警
*/
private void checkClusterAlert(MongoDBClusterMonitor monitorData) {
try {
String alertType = null;
String alertLevel = null;
String alertMessage = null;

// 检查连接使用率告警
if (monitorData.getConnectionUsage() > 90) {
alertType = "MONGODB_CONNECTION_HIGH";
alertLevel = "CRITICAL";
alertMessage = String.format("MongoDB连接使用率过高: %.2f%%", monitorData.getConnectionUsage());
} else if (monitorData.getConnectionUsage() > 80) {
alertType = "MONGODB_CONNECTION_WARNING";
alertLevel = "WARNING";
alertMessage = String.format("MongoDB连接使用率较高: %.2f%%", monitorData.getConnectionUsage());
}

// 检查内存使用率告警
if (monitorData.getMemoryUsage() > 90) {
alertType = "MONGODB_MEMORY_HIGH";
alertLevel = "CRITICAL";
alertMessage = String.format("MongoDB内存使用率过高: %.2f%%", monitorData.getMemoryUsage());
} else if (monitorData.getMemoryUsage() > 80) {
alertType = "MONGODB_MEMORY_WARNING";
alertLevel = "WARNING";
alertMessage = String.format("MongoDB内存使用率较高: %.2f%%", monitorData.getMemoryUsage());
}

// 检查副本集状态告警
if (!"healthy".equals(monitorData.getReplicaSetStatus())) {
alertType = "MONGODB_REPLICASET_UNHEALTHY";
alertLevel = "WARNING";
alertMessage = String.format("MongoDB副本集状态异常: %s", monitorData.getReplicaSetStatus());
}

// 发送告警
if (alertType != null) {
sendClusterAlert(monitorData, alertType, alertLevel, alertMessage);
}

} catch (Exception e) {
log.error("检查集群告警失败: {}", e.getMessage(), e);
}
}

/**
* 检查副本集告警
*/
private void checkReplicaSetAlert(MongoDBReplicaSetMonitor replicaSetMonitor) {
try {
String alertType = null;
String alertLevel = null;
String alertMessage = null;

// 检查节点状态告警
if (!"PRIMARY".equals(replicaSetMonitor.getNodeRole()) &&
!"SECONDARY".equals(replicaSetMonitor.getNodeRole())) {
alertType = "MONGODB_NODE_DOWN";
alertLevel = "CRITICAL";
alertMessage = String.format("MongoDB节点状态异常: %s", replicaSetMonitor.getNodeName());
}

// 检查复制延迟告警
if (replicaSetMonitor.getReplicationLag() > 10000) {
alertType = "MONGODB_REPLICATION_LAG";
alertLevel = "WARNING";
alertMessage = String.format("MongoDB复制延迟过高: %s, %dms",
replicaSetMonitor.getNodeName(), replicaSetMonitor.getReplicationLag());
}

// 发送告警
if (alertType != null) {
sendReplicaSetAlert(replicaSetMonitor, alertType, alertLevel, alertMessage);
}

} catch (Exception e) {
log.error("检查副本集告警失败: {}", e.getMessage(), e);
}
}

/**
* 发送集群告警
*/
private void sendClusterAlert(MongoDBClusterMonitor monitorData, String alertType, String alertLevel, String alertMessage) {
try {
String alertKey = "mongodb:cluster:alert:" + monitorData.getClusterName() + ":" + 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("发送集群告警: clusterName={}, type={}, level={}",
monitorData.getClusterName(), alertType, alertLevel);
}

} catch (Exception e) {
log.error("发送集群告警失败: {}", e.getMessage(), e);
}
}

/**
* 发送副本集告警
*/
private void sendReplicaSetAlert(MongoDBReplicaSetMonitor replicaSetMonitor, String alertType, String alertLevel, String alertMessage) {
try {
String alertKey = "mongodb:replicaset:alert:" + replicaSetMonitor.getNodeName() + ":" + 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(replicaSetMonitor.getNodeName());

alertService.sendAlert(alert);

redisTemplate.opsForValue().set(alertKey, "1", Duration.ofMinutes(5));

log.warn("发送副本集告警: nodeName={}, type={}, level={}",
replicaSetMonitor.getNodeName(), alertType, alertLevel);
}

} catch (Exception e) {
log.error("发送副本集告警失败: {}", e.getMessage(), e);
}
}

/**
* 获取实时集群数据
*/
public MongoDBClusterMonitor getRealTimeClusterData(String clusterName) {
String cacheKey = "mongodb:cluster:" + clusterName;
return (MongoDBClusterMonitor) redisTemplate.opsForValue().get(cacheKey);
}

/**
* 获取实时副本集数据
*/
public MongoDBReplicaSetMonitor getRealTimeReplicaSetData(String nodeName) {
String cacheKey = "mongodb:replicaset:" + nodeName;
return (MongoDBReplicaSetMonitor) redisTemplate.opsForValue().get(cacheKey);
}

/**
* 获取主机名
*/
private String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "unknown";
}
}

/**
* 获取本地IP地址
*/
private String getLocalIpAddress() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
return "127.0.0.1";
}
}

/**
* 关闭MongoDB客户端
*/
@PreDestroy
public void shutdownMongoDBClient() {
try {
if (mongoClient != null) {
mongoClient.close();
}

log.info("MongoDB客户端关闭成功");

} catch (Exception e) {
log.error("关闭MongoDB客户端失败: {}", e.getMessage(), e);
}
}
}

/**
* MongoDB集群信息实体类
*/
@Data
public class MongoDBClusterInfo {
private String clusterName; // 集群名称
private String clusterStatus; // 集群状态
private String replicaSetStatus; // 副本集状态
private Integer nodeCount; // 节点数量
private Integer databaseCount; // 数据库数量
private Integer collectionCount; // 集合数量
private Long totalDocuments; // 总文档数
private Long totalSize; // 总大小
private Integer primaryNodes; // 主节点数量
private Integer secondaryNodes; // 从节点数量
private Integer arbiterNodes; // 仲裁节点数量
private Long operationsPerSecond; // 每秒操作数
private Long queriesPerSecond; // 每秒查询数
private Long insertsPerSecond; // 每秒插入数
private Long updatesPerSecond; // 每秒更新数
private Long deletesPerSecond; // 每秒删除数
private Double avgQueryTime; // 平均查询时间
private Long connections; // 连接数
private Long maxConnections; // 最大连接数
private Double connectionUsage; // 连接使用率
private Long memoryUsed; // 内存使用量
private Long memoryTotal; // 总内存
private Double memoryUsage; // 内存使用率
private Long diskUsed; // 磁盘使用量
private Long diskTotal; // 总磁盘空间
private Double diskUsage; // 磁盘使用率
}

4. MongoDB管理服务

4.1 MongoDB管理服务

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
/**
* MongoDB管理服务
* 提供MongoDB集群管理功能
*/
@Service
public class MongoDBManagementService {

@Autowired
private MongoClient mongoClient;

@Autowired
private AlertService alertService;

/**
* 创建数据库
*/
public void createDatabase(String databaseName) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);

// 创建一个临时集合来确保数据库被创建
MongoCollection<Document> collection = database.getCollection("_temp");
collection.insertOne(new Document("_temp", true));
collection.drop();

log.info("创建数据库成功: databaseName={}", databaseName);

} catch (Exception e) {
log.error("创建数据库失败: databaseName={}, error={}", databaseName, e.getMessage(), e);
}
}

/**
* 删除数据库
*/
public void dropDatabase(String databaseName) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);
database.drop();

log.info("删除数据库成功: databaseName={}", databaseName);

} catch (Exception e) {
log.error("删除数据库失败: databaseName={}, error={}", databaseName, e.getMessage(), e);
}
}

/**
* 创建集合
*/
public void createCollection(String databaseName, String collectionName) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);
database.createCollection(collectionName);

log.info("创建集合成功: databaseName={}, collectionName={}", databaseName, collectionName);

} catch (Exception e) {
log.error("创建集合失败: databaseName={}, collectionName={}, error={}",
databaseName, collectionName, e.getMessage(), e);
}
}

/**
* 删除集合
*/
public void dropCollection(String databaseName, String collectionName) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(collectionName);
collection.drop();

log.info("删除集合成功: databaseName={}, collectionName={}", databaseName, collectionName);

} catch (Exception e) {
log.error("删除集合失败: databaseName={}, collectionName={}, error={}",
databaseName, collectionName, e.getMessage(), e);
}
}

/**
* 创建索引
*/
public void createIndex(String databaseName, String collectionName, String fieldName, String indexType) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(collectionName);

IndexOptions indexOptions = new IndexOptions();
if ("asc".equals(indexType)) {
collection.createIndex(Indexes.ascending(fieldName), indexOptions);
} else if ("desc".equals(indexType)) {
collection.createIndex(Indexes.descending(fieldName), indexOptions);
} else if ("text".equals(indexType)) {
collection.createIndex(Indexes.text(fieldName), indexOptions);
}

log.info("创建索引成功: databaseName={}, collectionName={}, fieldName={}, indexType={}",
databaseName, collectionName, fieldName, indexType);

} catch (Exception e) {
log.error("创建索引失败: databaseName={}, collectionName={}, fieldName={}, error={}",
databaseName, collectionName, fieldName, e.getMessage(), e);
}
}

/**
* 删除索引
*/
public void dropIndex(String databaseName, String collectionName, String indexName) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(collectionName);
collection.dropIndex(indexName);

log.info("删除索引成功: databaseName={}, collectionName={}, indexName={}",
databaseName, collectionName, indexName);

} catch (Exception e) {
log.error("删除索引失败: databaseName={}, collectionName={}, indexName={}, error={}",
databaseName, collectionName, indexName, e.getMessage(), e);
}
}

/**
* 获取数据库列表
*/
public List<String> getDatabases() {
try {
List<String> databaseNames = mongoClient.listDatabaseNames().into(new ArrayList<>());

// 过滤系统数据库
return databaseNames.stream()
.filter(name -> !name.equals("admin") && !name.equals("local") && !name.equals("config"))
.collect(Collectors.toList());

} catch (Exception e) {
log.error("获取数据库列表失败: {}", e.getMessage(), e);
return new ArrayList<>();
}
}

/**
* 获取集合列表
*/
public List<String> getCollections(String databaseName) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);
return database.listCollectionNames().into(new ArrayList<>());

} catch (Exception e) {
log.error("获取集合列表失败: databaseName={}, error={}", databaseName, e.getMessage(), e);
return new ArrayList<>();
}
}

/**
* 获取索引列表
*/
public List<Document> getIndexes(String databaseName, String collectionName) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(collectionName);

return collection.listIndexes().into(new ArrayList<>());

} catch (Exception e) {
log.error("获取索引列表失败: databaseName={}, collectionName={}, error={}",
databaseName, collectionName, e.getMessage(), e);
return new ArrayList<>();
}
}

/**
* 执行查询
*/
public List<Document> executeQuery(String databaseName, String collectionName, String query) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(collectionName);

Document queryDoc = Document.parse(query);
return collection.find(queryDoc).into(new ArrayList<>());

} catch (Exception e) {
log.error("执行查询失败: databaseName={}, collectionName={}, query={}, error={}",
databaseName, collectionName, query, e.getMessage(), e);
return new ArrayList<>();
}
}

/**
* 获取集合统计信息
*/
public Document getCollectionStats(String databaseName, String collectionName) {
try {
MongoDatabase database = mongoClient.getDatabase(databaseName);
return database.runCommand(new Document("collStats", collectionName));

} catch (Exception e) {
log.error("获取集合统计信息失败: databaseName={}, collectionName={}, error={}",
databaseName, collectionName, e.getMessage(), e);
return new Document();
}
}

/**
* 获取副本集状态
*/
public Document getReplicaSetStatus() {
try {
MongoDatabase adminDatabase = mongoClient.getDatabase("admin");
return adminDatabase.runCommand(new Document("replSetGetStatus", 1));

} catch (Exception e) {
log.error("获取副本集状态失败: {}", e.getMessage(), e);
return new Document();
}
}

/**
* 获取服务器状态
*/
public Document getServerStatus() {
try {
MongoDatabase adminDatabase = mongoClient.getDatabase("admin");
return adminDatabase.runCommand(new Document("serverStatus", 1));

} catch (Exception e) {
log.error("获取服务器状态失败: {}", e.getMessage(), e);
return new Document();
}
}
}

5. 总结

本文详细介绍了MongoDB数据库运维监控与管理的完整解决方案,包括:

5.1 核心技术点

  1. 集群监控: 实时监控MongoDB集群和节点状态
  2. 副本集管理: 管理副本集和故障切换
  3. 性能监控: 监控查询性能、连接数、内存使用
  4. 索引管理: 管理索引设计和查询优化
  5. 告警通知: 多级告警、智能通知

5.2 架构优势

  1. 实时监控: 10秒间隔的实时MongoDB数据采集
  2. 智能告警: 基于阈值的智能告警机制
  3. 自动化管理: 自动化的数据库和集合管理
  4. 多维度分析: 集群、副本集、性能等多维度分析

5.3 最佳实践

  1. 监控策略: 设置合理的MongoDB监控阈值
  2. 管理策略: 根据业务需求执行数据管理
  3. 性能优化: 合理配置MongoDB参数
  4. 预防措施: 提前预防MongoDB集群问题

通过以上架构设计,可以构建完善的MongoDB运维监控系统,实现MongoDB集群的有效管理和优化。