1. MongoDB副本集三节点硬件配置概述

MongoDB副本集三节点4核8GB SSD50GB配置是中小型企业级应用的标准配置,通过合理的资源分配和优化配置,可以实现高可用、高性能的数据库服务。本文将详细介绍在这种硬件配置下的MongoDB副本集部署、配置优化、性能调优以及运维管理的最佳实践。

1.1 硬件配置分析

1.1.1 硬件规格

  • CPU: 4核心处理器
  • 内存: 8GB RAM
  • 存储: 50GB SSD
  • 网络: 千兆网络
  • 节点数: 3个节点(1主2从)

1.1.2 资源分配策略

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
#!/bin/bash
# MongoDB副本集三节点资源分配策略
# @author 运维实战

echo "=== MongoDB副本集三节点资源分配策略 ==="

cat << 'EOF'
资源分配策略:

1. 内存分配 (8GB总内存)
- 系统预留: 2GB (25%)
- MongoDB缓存: 4GB (50%)
- 操作系统缓存: 2GB (25%)

2. 存储分配 (50GB SSD)
- 系统分区: 10GB (20%)
- 数据分区: 30GB (60%)
- 日志分区: 10GB (20%)

3. CPU分配 (4核心)
- 系统进程: 1核心 (25%)
- MongoDB进程: 2核心 (50%)
- 其他服务: 1核心 (25%)

4. 网络分配
- 副本集通信: 50%
- 客户端连接: 30%
- 系统网络: 20%
EOF

echo "资源分配策略说明完成"

1.2 副本集架构设计

1.2.1 三节点架构

  • 主节点(Primary): 处理所有写操作和读操作
  • 从节点1(Secondary1): 复制主节点数据,处理读操作
  • 从节点2(Secondary2): 复制主节点数据,处理读操作

1.2.2 高可用性保证

  • 自动故障转移: 主节点故障时自动选举新主节点
  • 数据冗余: 三副本数据保证数据安全
  • 读写分离: 支持读写分离提升性能

2. 副本集部署配置

2.1 系统环境准备

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
#!/bin/bash
# MongoDB副本集三节点系统环境准备脚本
# @author 运维实战

# 配置变量
REPLICA_SET_NAME="rs0"
MONGO_PORT=27017
DATA_DIR="/data/mongodb"
LOG_DIR="/var/log/mongodb"
CONFIG_DIR="/etc/mongodb"
ADMIN_USER="admin"
ADMIN_PASS="admin123"

# 系统优化配置
optimize_system_config() {
echo "优化系统配置..."

# 配置系统参数
cat > /etc/sysctl.conf << EOF
# MongoDB系统优化配置
# @author 运维实战

# 网络优化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 60
net.ipv4.tcp_keepalive_probes = 3

# 内存优化
vm.swappiness = 1
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5
vm.overcommit_memory = 1

# 文件系统优化
fs.file-max = 2097152
fs.aio-max-nr = 1048576
EOF

# 应用系统参数
sysctl -p

# 配置文件描述符限制
cat > /etc/security/limits.conf << EOF
# MongoDB文件描述符限制
# @author 运维实战

mongodb soft nofile 65535
mongodb hard nofile 65535
mongodb soft nproc 32768
mongodb hard nproc 32768
EOF

echo "系统配置优化完成"
}

# 创建目录结构
create_directories() {
echo "创建MongoDB目录结构..."

# 创建数据目录
mkdir -p $DATA_DIR/{primary,secondary1,secondary2}
chown -R mongodb:mongodb $DATA_DIR

# 创建日志目录
mkdir -p $LOG_DIR
chown -R mongodb:mongodb $LOG_DIR

# 创建配置目录
mkdir -p $CONFIG_DIR
chown -R mongodb:mongodb $CONFIG_DIR

# 设置目录权限
chmod 755 $DATA_DIR
chmod 755 $LOG_DIR
chmod 755 $CONFIG_DIR

echo "目录结构创建完成"
}

# 配置SSD优化
configure_ssd_optimization() {
echo "配置SSD优化..."

# 检查SSD设备
local ssd_device=$(lsblk -d -o name,rota | grep -v "1" | head -1 | awk '{print $1}')

if [ -n "$ssd_device" ]; then
echo "检测到SSD设备: $ssd_device"

# 配置SSD调度器
echo noop > /sys/block/$ssd_device/queue/scheduler

# 配置SSD参数
echo 0 > /sys/block/$ssd_device/queue/rotational
echo 1 > /sys/block/$ssd_device/queue/nomerges

# 配置TRIM支持
systemctl enable fstrim.timer
systemctl start fstrim.timer

echo "SSD优化配置完成"
else
echo "未检测到SSD设备,跳过SSD优化"
fi
}

# 配置内存优化
configure_memory_optimization() {
echo "配置内存优化..."

# 配置透明大页
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag

# 配置内存分配策略
echo 1 > /proc/sys/vm/overcommit_memory
echo 1 > /proc/sys/vm/swappiness

# 配置内存回收
echo 5 > /proc/sys/vm/dirty_background_ratio
echo 15 > /proc/sys/vm/dirty_ratio

echo "内存优化配置完成"
}

# 主函数
main() {
echo "开始MongoDB副本集三节点系统环境准备..."

optimize_system_config
create_directories
configure_ssd_optimization
configure_memory_optimization

echo "MongoDB副本集三节点系统环境准备完成!"
}

# 执行主函数
main "$@"

2.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
#!/bin/bash
# MongoDB副本集三节点配置文件生成脚本
# @author 运维实战

# 配置变量
REPLICA_SET_NAME="rs0"
MONGO_PORT=27017
DATA_DIR="/data/mongodb"
LOG_DIR="/var/log/mongodb"
CONFIG_DIR="/etc/mongodb"

# 生成主节点配置文件
generate_primary_config() {
echo "生成主节点配置文件..."

cat > $CONFIG_DIR/mongod-primary.conf << EOF
# MongoDB主节点配置文件 (4核8GB SSD50GB)
# @author 运维实战

# 存储配置
storage:
dbPath: $DATA_DIR/primary
journal:
enabled: true
commitIntervalMs: 100
wiredTiger:
engineConfig:
cacheSizeGB: 2
journalCompressor: snappy
directoryForIndexes: true
eviction: (threads_min=2,threads_max=4)
collectionConfig:
blockCompressor: snappy
indexConfig:
prefixCompression: true
logConfig:
compressor: snappy

# 网络配置
net:
port: $MONGO_PORT
bindIp: 0.0.0.0
maxIncomingConnections: 500
compression:
compressors: snappy,zstd
serviceExecutor: adaptive

# 日志配置
systemLog:
destination: file
path: $LOG_DIR/mongod-primary.log
logAppend: true
logRotate: reopen
verbosity: 1
component:
accessControl:
verbosity: 1
command:
verbosity: 1
replication:
verbosity: 1

# 进程管理
processManagement:
fork: true
pidFilePath: $DATA_DIR/primary/mongod.pid
timeZoneInfo: /usr/share/zoneinfo

# 副本集配置
replication:
replSetName: $REPLICA_SET_NAME
oplogSizeMB: 512

# 安全配置
security:
authorization: enabled
keyFile: $CONFIG_DIR/keyfile

# 性能优化
operationProfiling:
slowOpThresholdMs: 100
mode: slowOp

# 监控配置
setParameter:
enableLocalhostAuthBypass: false
logLevel: 1
maxConns: 500
connPoolMaxShardedConnsPerHost: 100
connPoolMaxConnsPerHost: 100
wiredTigerConcurrentReadTransactions: 64
wiredTigerConcurrentWriteTransactions: 64
wiredTigerEngineRuntimeConfig: "cache_size=2GB,eviction=(threads_min=2,threads_max=4)"
EOF

echo "主节点配置文件生成完成"
}

# 生成从节点1配置文件
generate_secondary1_config() {
echo "生成从节点1配置文件..."

cat > $CONFIG_DIR/mongod-secondary1.conf << EOF
# MongoDB从节点1配置文件 (4核8GB SSD50GB)
# @author 运维实战

# 存储配置
storage:
dbPath: $DATA_DIR/secondary1
journal:
enabled: true
commitIntervalMs: 100
wiredTiger:
engineConfig:
cacheSizeGB: 2
journalCompressor: snappy
directoryForIndexes: true
eviction: (threads_min=2,threads_max=4)
collectionConfig:
blockCompressor: snappy
indexConfig:
prefixCompression: true
logConfig:
compressor: snappy

# 网络配置
net:
port: $((MONGO_PORT + 1))
bindIp: 0.0.0.0
maxIncomingConnections: 500
compression:
compressors: snappy,zstd
serviceExecutor: adaptive

# 日志配置
systemLog:
destination: file
path: $LOG_DIR/mongod-secondary1.log
logAppend: true
logRotate: reopen
verbosity: 1
component:
accessControl:
verbosity: 1
command:
verbosity: 1
replication:
verbosity: 1

# 进程管理
processManagement:
fork: true
pidFilePath: $DATA_DIR/secondary1/mongod.pid
timeZoneInfo: /usr/share/zoneinfo

# 副本集配置
replication:
replSetName: $REPLICA_SET_NAME
oplogSizeMB: 512

# 安全配置
security:
authorization: enabled
keyFile: $CONFIG_DIR/keyfile

# 性能优化
operationProfiling:
slowOpThresholdMs: 100
mode: slowOp

# 监控配置
setParameter:
enableLocalhostAuthBypass: false
logLevel: 1
maxConns: 500
connPoolMaxShardedConnsPerHost: 100
connPoolMaxConnsPerHost: 100
wiredTigerConcurrentReadTransactions: 64
wiredTigerConcurrentWriteTransactions: 64
wiredTigerEngineRuntimeConfig: "cache_size=2GB,eviction=(threads_min=2,threads_max=4)"
EOF

echo "从节点1配置文件生成完成"
}

# 生成从节点2配置文件
generate_secondary2_config() {
echo "生成从节点2配置文件..."

cat > $CONFIG_DIR/mongod-secondary2.conf << EOF
# MongoDB从节点2配置文件 (4核8GB SSD50GB)
# @author 运维实战

# 存储配置
storage:
dbPath: $DATA_DIR/secondary2
journal:
enabled: true
commitIntervalMs: 100
wiredTiger:
engineConfig:
cacheSizeGB: 2
journalCompressor: snappy
directoryForIndexes: true
eviction: (threads_min=2,threads_max=4)
collectionConfig:
blockCompressor: snappy
indexConfig:
prefixCompression: true
logConfig:
compressor: snappy

# 网络配置
net:
port: $((MONGO_PORT + 2))
bindIp: 0.0.0.0
maxIncomingConnections: 500
compression:
compressors: snappy,zstd
serviceExecutor: adaptive

# 日志配置
systemLog:
destination: file
path: $LOG_DIR/mongod-secondary2.log
logAppend: true
logRotate: reopen
verbosity: 1
component:
accessControl:
verbosity: 1
command:
verbosity: 1
replication:
verbosity: 1

# 进程管理
processManagement:
fork: true
pidFilePath: $DATA_DIR/secondary2/mongod.pid
timeZoneInfo: /usr/share/zoneinfo

# 副本集配置
replication:
replSetName: $REPLICA_SET_NAME
oplogSizeMB: 512

# 安全配置
security:
authorization: enabled
keyFile: $CONFIG_DIR/keyfile

# 性能优化
operationProfiling:
slowOpThresholdMs: 100
mode: slowOp

# 监控配置
setParameter:
enableLocalhostAuthBypass: false
logLevel: 1
maxConns: 500
connPoolMaxShardedConnsPerHost: 100
connPoolMaxConnsPerHost: 100
wiredTigerConcurrentReadTransactions: 64
wiredTigerConcurrentWriteTransactions: 64
wiredTigerEngineRuntimeConfig: "cache_size=2GB,eviction=(threads_min=2,threads_max=4)"
EOF

echo "从节点2配置文件生成完成"
}

# 生成密钥文件
generate_keyfile() {
echo "生成MongoDB密钥文件..."

# 生成随机密钥
openssl rand -base64 756 > $CONFIG_DIR/keyfile
chmod 600 $CONFIG_DIR/keyfile
chown mongodb:mongodb $CONFIG_DIR/keyfile

echo "密钥文件生成完成"
}

# 主函数
main() {
echo "开始生成MongoDB副本集三节点配置文件..."

generate_primary_config
generate_secondary1_config
generate_secondary2_config
generate_keyfile

echo "MongoDB副本集三节点配置文件生成完成!"
}

# 执行主函数
main "$@"

2.3 副本集部署脚本

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
#!/bin/bash
# MongoDB副本集三节点部署脚本
# @author 运维实战

# 配置变量
REPLICA_SET_NAME="rs0"
MONGO_PORT=27017
DATA_DIR="/data/mongodb"
LOG_DIR="/var/log/mongodb"
CONFIG_DIR="/etc/mongodb"
ADMIN_USER="admin"
ADMIN_PASS="admin123"

# 启动MongoDB服务
start_mongodb_services() {
echo "启动MongoDB副本集三节点服务..."

# 启动主节点
echo "启动主节点..."
mongod --config $CONFIG_DIR/mongod-primary.conf
sleep 5

# 启动从节点1
echo "启动从节点1..."
mongod --config $CONFIG_DIR/mongod-secondary1.conf
sleep 5

# 启动从节点2
echo "启动从节点2..."
mongod --config $CONFIG_DIR/mongod-secondary2.conf
sleep 5

echo "MongoDB副本集三节点服务启动完成"
}

# 初始化副本集
initialize_replica_set() {
echo "初始化MongoDB副本集三节点..."

# 连接到主节点并初始化副本集
mongo --port $MONGO_PORT << EOF
// 初始化MongoDB副本集三节点
// @author 运维实战

// 初始化副本集配置
rs.initiate({
_id: "$REPLICA_SET_NAME",
members: [
{
_id: 0,
host: "localhost:$MONGO_PORT",
priority: 2,
tags: { "dc": "primary", "role": "primary", "hardware": "4c8g" }
},
{
_id: 1,
host: "localhost:$((MONGO_PORT + 1))",
priority: 1,
tags: { "dc": "secondary", "role": "secondary", "hardware": "4c8g" }
},
{
_id: 2,
host: "localhost:$((MONGO_PORT + 2))",
priority: 1,
tags: { "dc": "secondary", "role": "secondary", "hardware": "4c8g" }
}
],
settings: {
heartbeatIntervalMillis: 2000,
electionTimeoutMillis: 10000,
catchUpTimeoutMillis: 2000,
catchUpTakeoverDelayMillis: 30000
}
});

// 等待副本集初始化完成
print("等待副本集初始化完成...");
while (rs.status().ok !== 1) {
sleep(1000);
}

// 检查副本集状态
print("副本集状态:");
rs.status();

print("副本集三节点初始化完成");
EOF

echo "副本集三节点初始化完成"
}

# 创建用户账户
create_users() {
echo "创建MongoDB用户账户..."

# 等待副本集稳定
sleep 10

# 创建管理员用户
mongo --port $MONGO_PORT << EOF
// 创建MongoDB用户账户
// @author 运维实战

use admin;

// 创建管理员用户
db.createUser({
user: "$ADMIN_USER",
pwd: "$ADMIN_PASS",
roles: [
{ role: "root", db: "admin" },
{ role: "clusterAdmin", db: "admin" },
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" }
]
});

// 创建应用用户
use appdb;
db.createUser({
user: "appuser",
pwd: "app123",
roles: [
{ role: "readWrite", db: "appdb" },
{ role: "read", db: "appdb" }
]
});

// 创建只读用户
use appdb;
db.createUser({
user: "readonly",
pwd: "read123",
roles: [
{ role: "read", db: "appdb" }
]
});

print("用户账户创建完成");
EOF

echo "用户账户创建完成"
}

# 配置副本集优化
configure_replica_set_optimization() {
echo "配置副本集优化..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 配置副本集优化
// @author 运维实战

use admin;

// 配置副本集设置
var config = rs.conf();
config.settings.heartbeatIntervalMillis = 2000;
config.settings.electionTimeoutMillis = 10000;
config.settings.catchUpTimeoutMillis = 2000;
config.settings.catchUpTakeoverDelayMillis = 30000;

// 应用配置
rs.reconfig(config);

// 设置从节点读取偏好
rs.slaveOk();

// 配置读写分离
db.getMongo().setReadPref("secondaryPreferred");

// 配置写入关注
db.getMongo().setWriteConcern({
w: "majority",
j: true,
wtimeout: 5000
});

print("副本集优化配置完成");
EOF

echo "副本集优化配置完成"
}

# 验证部署结果
verify_deployment() {
echo "验证MongoDB副本集三节点部署结果..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 验证MongoDB副本集三节点部署结果
// @author 运维实战

use admin;

// 检查副本集状态
print("=== 副本集部署验证 ===");
var status = rs.status();
print("副本集成员数量: " + status.members.length);

// 检查每个成员状态
for (var i = 0; i < status.members.length; i++) {
var member = status.members[i];
print("成员 " + (i + 1) + ": " + member.name + " 状态: " + member.stateStr + " 优先级: " + member.priority);
}

// 检查主节点
print("\n=== 主节点检查 ===");
var primary = rs.isMaster();
print("主节点: " + primary.primary);
print("副本集名称: " + primary.setName);

// 检查数据同步
print("\n=== 数据同步检查 ===");
rs.printSlaveReplicationInfo();

// 检查复制延迟
print("\n=== 复制延迟检查 ===");
var members = status.members;
for (var i = 0; i < members.length; i++) {
var member = members[i];
if (member.state === 2) { // 从节点
var lag = member.optimeDate - member.lastHeartbeat;
print("从节点 " + member.name + " 复制延迟: " + lag + " ms");
}
}

// 检查oplog状态
print("\n=== Oplog状态检查 ===");
use local;
var oplogStats = db.oplog.rs.stats();
print("Oplog大小: " + oplogStats.size + " bytes");
print("Oplog使用率: " + (oplogStats.storageSize / oplogStats.maxSize * 100).toFixed(2) + "%");

print("\n副本集三节点部署验证完成");
EOF

echo "副本集三节点部署验证完成"
}

# 主函数
main() {
echo "开始部署MongoDB副本集三节点..."

start_mongodb_services
initialize_replica_set
create_users
configure_replica_set_optimization
verify_deployment

echo "MongoDB副本集三节点部署完成!"
echo "主节点: localhost:$MONGO_PORT"
echo "从节点1: localhost:$((MONGO_PORT + 1))"
echo "从节点2: localhost:$((MONGO_PORT + 2))"
echo "管理员用户: $ADMIN_USER"
echo "管理员密码: $ADMIN_PASS"
}

# 执行主函数
main "$@"

3. 性能优化配置

3.1 性能优化脚本

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
#!/bin/bash
# MongoDB副本集三节点性能优化脚本
# @author 运维实战

# 配置变量
MONGO_PORT=27017
ADMIN_USER="admin"
ADMIN_PASS="admin123"

# 优化内存配置
optimize_memory_config() {
echo "优化内存配置..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 优化内存配置
// @author 运维实战

use admin;

// 获取当前内存配置
var serverStatus = db.serverStatus();
print("当前内存使用情况:");
print(" 物理内存: " + serverStatus.mem.resident + " MB");
print(" 虚拟内存: " + serverStatus.mem.virtual + " MB");
print(" 映射内存: " + serverStatus.mem.mapped + " MB");

// 配置WiredTiger缓存 (2GB for 8GB RAM)
db.adminCommand({
setParameter: 1,
wiredTigerEngineRuntimeConfig: "cache_size=2GB,eviction=(threads_min=2,threads_max=4)"
});

// 配置连接池
db.adminCommand({
setParameter: 1,
maxConns: 500,
connPoolMaxShardedConnsPerHost: 100,
connPoolMaxConnsPerHost: 100
});

// 配置并发事务
db.adminCommand({
setParameter: 1,
wiredTigerConcurrentReadTransactions: 64,
wiredTigerConcurrentWriteTransactions: 64
});

print("内存配置优化完成");
EOF

echo "内存配置优化完成"
}

# 优化存储配置
optimize_storage_config() {
echo "优化存储配置..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 优化存储配置
// @author 运维实战

use admin;

// 配置WiredTiger存储引擎
db.adminCommand({
setParameter: 1,
wiredTigerEngineRuntimeConfig: "cache_size=2GB,eviction=(threads_min=2,threads_max=4),checkpoint=(wait=60,log_size=1GB)"
});

// 配置压缩
db.adminCommand({
setParameter: 1,
wiredTigerCollectionBlockCompressor: "snappy",
wiredTigerIndexPrefixCompression: true
});

// 配置日志
db.adminCommand({
setParameter: 1,
wiredTigerLogCompressor: "snappy",
wiredTigerLogFileMax: "2GB"
});

print("存储配置优化完成");
EOF

echo "存储配置优化完成"
}

# 优化网络配置
optimize_network_config() {
echo "优化网络配置..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 优化网络配置
// @author 运维实战

use admin;

// 配置网络参数
db.adminCommand({
setParameter: 1,
maxIncomingConnections: 500,
connPoolMaxShardedConnsPerHost: 100,
connPoolMaxConnsPerHost: 100
});

// 配置压缩
db.adminCommand({
setParameter: 1,
networkMessageCompressors: "snappy,zstd"
});

// 配置超时
db.adminCommand({
setParameter: 1,
socketTimeoutMS: 30000,
connectTimeoutMS: 10000
});

print("网络配置优化完成");
EOF

echo "网络配置优化完成"
}

# 优化副本集配置
optimize_replica_set_config() {
echo "优化副本集配置..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 优化副本集配置
// @author 运维实战

use admin;

// 获取当前配置
var config = rs.conf();

// 优化副本集设置
config.settings.heartbeatIntervalMillis = 2000;
config.settings.electionTimeoutMillis = 10000;
config.settings.catchUpTimeoutMillis = 2000;
config.settings.catchUpTakeoverDelayMillis = 30000;

// 应用配置
rs.reconfig(config);

// 配置oplog大小 (512MB for 50GB SSD)
db.adminCommand({
setParameter: 1,
oplogSize: 512
});

print("副本集配置优化完成");
EOF

echo "副本集配置优化完成"
}

# 优化索引配置
optimize_index_config() {
echo "优化索引配置..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 优化索引配置
// @author 运维实战

use admin;

// 配置索引构建
db.adminCommand({
setParameter: 1,
maxIndexBuildMemoryUsageMegabytes: 512
});

// 配置后台索引构建
db.adminCommand({
setParameter: 1,
backgroundIndexBuildRetry: true
});

print("索引配置优化完成");
EOF

echo "索引配置优化完成"
}

# 验证性能优化效果
verify_performance_optimization() {
echo "验证性能优化效果..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 验证性能优化效果
// @author 运维实战

use admin;

// 获取服务器状态
var serverStatus = db.serverStatus();
print("=== 性能优化效果验证 ===");

// 内存使用情况
print("内存使用情况:");
print(" 物理内存: " + serverStatus.mem.resident + " MB");
print(" 虚拟内存: " + serverStatus.mem.virtual + " MB");
print(" 映射内存: " + serverStatus.mem.mapped + " MB");

// 连接情况
print("\n连接情况:");
print(" 当前连接数: " + serverStatus.connections.current);
print(" 可用连接数: " + serverStatus.connections.available);
print(" 总连接数: " + serverStatus.connections.totalCreated);

// 网络情况
print("\n网络情况:");
print(" 字节输入: " + serverStatus.network.bytesIn);
print(" 字节输出: " + serverStatus.network.bytesOut);
print(" 请求数: " + serverStatus.network.numRequests);

// 存储情况
print("\n存储情况:");
print(" 数据大小: " + serverStatus.storageSize);
print(" 索引大小: " + serverStatus.indexSize);
print(" 总大小: " + (serverStatus.storageSize + serverStatus.indexSize));

// 副本集情况
print("\n副本集情况:");
var status = rs.status();
print(" 成员数量: " + status.members.length);
print(" 主节点: " + status.primary);

// 检查性能阈值
var connections = serverStatus.connections;
if (connections.current > 400) {
print("警告: 连接数过高: " + connections.current);
}

var memory = serverStatus.mem;
if (memory.resident > 6000) {
print("警告: 内存使用过高: " + memory.resident + " MB");
}

print("\n性能优化效果验证完成");
EOF

echo "性能优化效果验证完成"
}

# 主函数
main() {
echo "开始MongoDB副本集三节点性能优化..."

optimize_memory_config
optimize_storage_config
optimize_network_config
optimize_replica_set_config
optimize_index_config
verify_performance_optimization

echo "MongoDB副本集三节点性能优化完成!"
}

# 执行主函数
main "$@"

4. 监控和运维管理

4.1 监控脚本

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
#!/bin/bash
# MongoDB副本集三节点监控脚本
# @author 运维实战

# 配置变量
MONGO_PORT=27017
ADMIN_USER="admin"
ADMIN_PASS="admin123"
LOG_FILE="/var/log/mongodb/monitor.log"
ALERT_EMAIL="admin@example.com"

# 记录日志
log_message() {
local message=$1
echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" >> $LOG_FILE
}

# 监控副本集状态
monitor_replica_set_status() {
echo "监控副本集状态..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 监控副本集状态
// @author 运维实战

use admin;

// 获取副本集状态
var status = rs.status();
var members = status.members;

print("=== 副本集状态监控 ===");
print("副本集成员数量: " + members.length);

// 检查每个成员状态
for (var i = 0; i < members.length; i++) {
var member = members[i];
var state = member.state;
var name = member.name;
var tags = member.tags || {};
var hardware = tags.hardware || "unknown";

print("成员 " + (i + 1) + ": " + name);
print(" 状态: " + member.stateStr);
print(" 优先级: " + member.priority);
print(" 硬件配置: " + hardware);

// 检查复制延迟
if (state === 2) { // 从节点
var lag = member.optimeDate - member.lastHeartbeat;
print(" 复制延迟: " + lag + " ms");

if (lag > 10000) {
print(" 警告: 复制延迟过高");
}
}

// 检查网络延迟
var lastHeartbeat = member.lastHeartbeat;
var now = new Date();
var networkLag = now - lastHeartbeat;
print(" 网络延迟: " + networkLag + " ms");

if (networkLag > 5000) {
print(" 警告: 网络延迟过高");
}
}

// 检查主节点
print("\n=== 主节点检查 ===");
var primary = rs.isMaster();
print("主节点: " + primary.primary);
print("副本集名称: " + primary.setName);
print("副本集版本: " + primary.setVersion);
EOF

log_message "副本集状态监控完成"
}

# 监控性能指标
monitor_performance_metrics() {
echo "监控性能指标..."

mongo --port $MONGO_PORT -u $ADMIN_USER -p $ADMIN_PASS --authenticationDatabase admin << EOF
// 监控性能指标
// @author 运维实战

use admin;

// 获取服务器状态
var serverStatus = db.serverStatus();

print("=== 性能指标监控 ===");

// 内存使用情况
print("内存使用情况:");
print(" 物理内存: " + serverStatus.mem.resident + " MB");
print(" 虚拟内存: " + serverStatus.mem.virtual + " MB");
print(" 映射内存: " + serverStatus.mem.mapped + " MB");

// 连接情况
print("\n连接情况:");
print(" 当前连接数: " + serverStatus.connections.current);
print(" 可用连接数: " + serverStatus.connections.available);
print(" 总连接数: " + serverStatus.connections.totalCreated);

// 网络情况
print("\n网络情况:");
print(" 字节输入: " + serverStatus.network.bytesIn);
print(" 字节输出: " + serverStatus.network.bytesOut);
print(" 请求数: " + serverStatus.network.numRequests);

// 操作情况
print("\n操作情况:");
print(" 插入操作: " + serverStatus.opcounters.insert);
print(" 查询操作: " + serverStatus.opcounters.query);
print(" 更新操作: " + serverStatus.opcounters.update);
print(" 删除操作: " + serverStatus.opcounters.delete);

// 存储情况
print("\n存储情况:");
print(" 数据大小: " + serverStatus.storageSize);
print(" 索引大小: " + serverStatus.indexSize);
print(" 总大小: " + (serverStatus.storageSize + serverStatus.indexSize));

// 检查性能阈值
var connections = serverStatus.connections;
if (connections.current > 400) {
print("警告: 连接数过高: " + connections.current);
}

var memory = serverStatus.mem;
if (memory.resident > 6000) {
print("警告: 内存使用过高: " + memory.resident + " MB");
}

var storage = serverStatus.storageSize + serverStatus.indexSize;
if (storage > 40000000000) { // 40GB
print("警告: 存储使用过高: " + (storage / 1024 / 1024 / 1024).toFixed(2) + " GB");
}
EOF

log_message "性能指标监控完成"
}

# 监控磁盘空间
monitor_disk_space() {
echo "监控磁盘空间..."

# 检查数据目录磁盘空间
local data_dir="/data/mongodb"
local disk_usage=$(df -h $data_dir | awk 'NR==2 {print $5}' | sed 's/%//')

if [ $disk_usage -gt 80 ]; then
echo "磁盘空间不足: $disk_usage%"
log_message "磁盘空间不足: $disk_usage%"
send_alert "MongoDB副本集磁盘空间不足: $disk_usage%"
else
echo "磁盘空间正常: $disk_usage%"
log_message "磁盘空间正常: $disk_usage%"
fi
}

# 监控日志文件
monitor_log_files() {
echo "监控日志文件..."

local log_dir="/var/log/mongodb"
local error_count=$(grep -c "ERROR" $log_dir/*.log 2>/dev/null || echo "0")
local warning_count=$(grep -c "WARNING" $log_dir/*.log 2>/dev/null || echo "0")

if [ $error_count -gt 0 ]; then
echo "发现 $error_count 个错误日志"
log_message "发现 $error_count 个错误日志"
send_alert "MongoDB副本集发现 $error_count 个错误日志"
fi

if [ $warning_count -gt 10 ]; then
echo "发现 $warning_count 个警告日志"
log_message "发现 $warning_count 个警告日志"
send_alert "MongoDB副本集发现 $warning_count 个警告日志"
fi

echo "日志监控完成"
}

# 发送告警
send_alert() {
local message=$1
echo "发送告警: $message"

# 发送邮件告警
echo "$message" | mail -s "MongoDB副本集三节点告警" $ALERT_EMAIL

log_message "告警发送完成: $message"
}

# 生成监控报告
generate_monitor_report() {
echo "生成监控报告..."

local report_file="/var/log/mongodb/monitor_report_$(date +%Y%m%d).txt"

cat > $report_file << EOF
MongoDB副本集三节点监控报告
生成时间: $(date)
硬件配置: 4核8GB SSD50GB
========================================

1. 副本集状态监控
$(monitor_replica_set_status)

2. 性能指标监控
$(monitor_performance_metrics)

3. 磁盘空间监控
$(monitor_disk_space)

4. 日志文件监控
$(monitor_log_files)

========================================
EOF

echo "监控报告生成完成: $report_file"
log_message "监控报告生成完成: $report_file"
}

# 主函数
main() {
echo "开始MongoDB副本集三节点监控..."

monitor_replica_set_status
monitor_performance_metrics
monitor_disk_space
monitor_log_files
generate_monitor_report

echo "MongoDB副本集三节点监控完成"
}

# 执行主函数
main "$@"

5. 总结

5.1 MongoDB副本集三节点最佳实践

  1. 硬件配置优化: 合理分配4核8GB内存和50GB SSD存储
  2. 资源分配策略: 系统预留2GB,MongoDB使用4GB,缓存2GB
  3. 存储优化: 利用SSD高性能特性,配置合适的压缩和日志
  4. 网络优化: 配置连接池和压缩提升网络性能
  5. 监控告警: 建立完善的监控和告警机制

5.2 性能优化建议

  • 内存配置: 2GB WiredTiger缓存,64个并发事务
  • 存储配置: Snappy压缩,2GB日志文件,60秒检查点
  • 网络配置: 500个最大连接,Snappy/Zstd压缩
  • 副本集配置: 2秒心跳间隔,10秒选举超时
  • 索引配置: 512MB索引构建内存,后台索引构建

5.3 运维管理要点

  • 日常监控: 定期检查副本集状态和性能指标
  • 容量管理: 监控磁盘空间使用,及时清理日志
  • 故障处理: 建立故障处理流程和应急预案
  • 备份策略: 制定数据备份和恢复策略
  • 安全加固: 加强访问控制和密钥管理

通过本文的MongoDB副本集三节点4核8GB SSD50GB运维实战指南,您可以掌握在这种硬件配置下的MongoDB副本集部署、配置优化、性能调优以及运维管理的最佳实践,构建稳定、高效的MongoDB副本集系统!