1. CPU运维监控概述

CPU是服务器性能的核心指标,CPU使用率过高会导致系统响应缓慢、服务不可用等问题。本文将详细介绍CPU监控、性能优化、问题诊断和自动化运维的完整解决方案,帮助运维人员有效管理CPU资源。

1.1 核心挑战

  1. CPU使用率监控: 实时监控CPU使用情况
  2. 性能瓶颈识别: 快速定位CPU性能瓶颈
  3. 资源优化: 优化CPU资源分配和使用
  4. 问题预警: 提前发现CPU相关问题
  5. 自动化运维: 实现CPU监控和优化的自动化

1.2 技术架构

1
2
3
4
5
CPU监控 → 数据采集 → 数据处理 → 告警通知 → 自动优化
↓ ↓ ↓ ↓ ↓
系统指标 → 监控代理 → 数据存储 → 告警引擎 → 运维脚本
↓ ↓ ↓ ↓ ↓
性能分析 → 趋势分析 → 异常检测 → 通知推送 → 自动调优

2. CPU监控系统

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!-- 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>

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

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

<!-- OSHI系统信息 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>6.4.0</version>
</dependency>

<!-- Sigar系统监控 -->
<dependency>
<groupId>org.hyperic</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>

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

<!-- Druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
</dependencies>

2.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
32
33
34
35
36
37
38
# application.yml
server:
port: 8080

spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000

redis:
host: localhost
port: 6379
database: 0
timeout: 5000

# CPU监控配置
cpu-monitor:
collection-interval: 5000 # 采集间隔(毫秒)
alert-threshold: 80 # 告警阈值(%)
critical-threshold: 95 # 严重告警阈值(%)
history-retention-days: 30 # 历史数据保留天数
enable-auto-optimization: true # 启用自动优化

# 告警配置
alert:
email:
enabled: true
smtp-host: smtp.qq.com
smtp-port: 587
username: alert@example.com
password: your-password
webhook:
enabled: true
url: http://localhost:8080/webhook/alert

3. CPU监控服务

3.1 CPU监控实体类

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
/**
* CPU监控数据实体类
* 存储CPU监控指标
*/
@Data
@TableName("cpu_monitor_data")
public class CpuMonitorData {

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

private String hostname; // 主机名

private String ip; // IP地址

private Double cpuUsage; // CPU使用率

private Double cpuUser; // 用户态CPU使用率

private Double cpuSystem; // 系统态CPU使用率

private Double cpuIdle; // 空闲CPU使用率

private Double cpuIowait; // IO等待CPU使用率

private Double loadAverage1m; // 1分钟负载平均值

private Double loadAverage5m; // 5分钟负载平均值

private Double loadAverage15m; // 15分钟负载平均值

private Integer cpuCores; // CPU核心数

private Long cpuFrequency; // CPU频率

private Date collectTime; // 采集时间

private Date createTime; // 创建时间
}

/**
* CPU告警记录实体类
*/
@Data
@TableName("cpu_alert_record")
public class CpuAlertRecord {

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

private String hostname; // 主机名

private String ip; // IP地址

private String alertType; // 告警类型

private String alertLevel; // 告警级别

private Double cpuUsage; // CPU使用率

private String alertMessage; // 告警消息

private String alertStatus; // 告警状态

private Date alertTime; // 告警时间

private Date resolveTime; // 解决时间

private String resolveMessage; // 解决说明
}

3.2 CPU监控服务

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
/**
* CPU监控服务
* 负责CPU数据的采集、存储和分析
*/
@Service
public class CpuMonitorService {

@Autowired
private CpuMonitorDataMapper cpuMonitorDataMapper;

@Autowired
private CpuAlertRecordMapper cpuAlertRecordMapper;

@Autowired
private RedisTemplate<String, Object> redisTemplate;

@Autowired
private AlertService alertService;

@Autowired
private SystemInfoService systemInfoService;

/**
* 采集CPU数据
* 定期采集CPU使用情况
*/
@Scheduled(fixedRate = 5000) // 每5秒执行一次
public void collectCpuData() {
try {
// 1. 获取系统信息
SystemInfo systemInfo = systemInfoService.getSystemInfo();

// 2. 创建CPU监控数据
CpuMonitorData cpuData = createCpuMonitorData(systemInfo);

// 3. 保存到数据库
cpuMonitorDataMapper.insert(cpuData);

// 4. 更新缓存
updateCpuCache(cpuData);

// 5. 检查告警条件
checkCpuAlert(cpuData);

// 6. 更新统计信息
updateCpuStatistics(cpuData);

log.debug("采集CPU数据: hostname={}, cpuUsage={}%",
cpuData.getHostname(), cpuData.getCpuUsage());

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

/**
* 创建CPU监控数据
*/
private CpuMonitorData createCpuMonitorData(SystemInfo systemInfo) {
CpuMonitorData cpuData = new CpuMonitorData();

// 设置基本信息
cpuData.setHostname(systemInfo.getHostname());
cpuData.setIp(systemInfo.getIp());
cpuData.setCollectTime(new Date());
cpuData.setCreateTime(new Date());

// 设置CPU信息
CpuInfo cpuInfo = systemInfo.getCpuInfo();
cpuData.setCpuUsage(cpuInfo.getUsage());
cpuData.setCpuUser(cpuInfo.getUser());
cpuData.setCpuSystem(cpuInfo.getSystem());
cpuData.setCpuIdle(cpuInfo.getIdle());
cpuData.setCpuIowait(cpuInfo.getIowait());

// 设置负载信息
LoadAverage loadAverage = systemInfo.getLoadAverage();
cpuData.setLoadAverage1m(loadAverage.getLoad1m());
cpuData.setLoadAverage5m(loadAverage.getLoad5m());
cpuData.setLoadAverage15m(loadAverage.getLoad15m());

// 设置CPU核心信息
cpuData.setCpuCores(cpuInfo.getCores());
cpuData.setCpuFrequency(cpuInfo.getFrequency());

return cpuData;
}

/**
* 更新CPU缓存
*/
private void updateCpuCache(CpuMonitorData cpuData) {
try {
String cacheKey = "cpu:realtime:" + cpuData.getHostname();
redisTemplate.opsForValue().set(cacheKey, cpuData, Duration.ofMinutes(5));

// 更新历史数据缓存
String historyKey = "cpu:history:" + cpuData.getHostname();
redisTemplate.opsForList().leftPush(historyKey, cpuData);
redisTemplate.opsForList().trim(historyKey, 0, 99); // 保留最近100条
redisTemplate.expire(historyKey, Duration.ofHours(1));

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

/**
* 检查CPU告警
*/
private void checkCpuAlert(CpuMonitorData cpuData) {
try {
String alertType = null;
String alertLevel = null;
String alertMessage = null;

// 检查CPU使用率告警
if (cpuData.getCpuUsage() >= 95) {
alertType = "CPU_CRITICAL";
alertLevel = "CRITICAL";
alertMessage = String.format("CPU使用率过高: %.2f%%", cpuData.getCpuUsage());
} else if (cpuData.getCpuUsage() >= 80) {
alertType = "CPU_HIGH";
alertLevel = "WARNING";
alertMessage = String.format("CPU使用率较高: %.2f%%", cpuData.getCpuUsage());
}

// 检查负载告警
if (cpuData.getLoadAverage1m() > cpuData.getCpuCores() * 2) {
alertType = "LOAD_HIGH";
alertLevel = "WARNING";
alertMessage = String.format("系统负载过高: %.2f", cpuData.getLoadAverage1m());
}

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

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

/**
* 发送CPU告警
*/
private void sendCpuAlert(CpuMonitorData cpuData, String alertType, String alertLevel, String alertMessage) {
try {
// 检查是否已经发送过相同告警
String alertKey = "cpu:alert:" + cpuData.getHostname() + ":" + alertType;
Boolean hasAlert = redisTemplate.hasKey(alertKey);

if (hasAlert == null || !hasAlert) {
// 创建告警记录
CpuAlertRecord alertRecord = new CpuAlertRecord();
alertRecord.setHostname(cpuData.getHostname());
alertRecord.setIp(cpuData.getIp());
alertRecord.setAlertType(alertType);
alertRecord.setAlertLevel(alertLevel);
alertRecord.setCpuUsage(cpuData.getCpuUsage());
alertRecord.setAlertMessage(alertMessage);
alertRecord.setAlertStatus("ACTIVE");
alertRecord.setAlertTime(new Date());

// 保存告警记录
cpuAlertRecordMapper.insert(alertRecord);

// 发送告警通知
alertService.sendCpuAlert(alertRecord);

// 设置告警缓存,5分钟内不重复发送
redisTemplate.opsForValue().set(alertKey, "1", Duration.ofMinutes(5));

log.warn("发送CPU告警: hostname={}, type={}, level={}",
cpuData.getHostname(), alertType, alertLevel);
}

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

/**
* 更新CPU统计信息
*/
private void updateCpuStatistics(CpuMonitorData cpuData) {
try {
String statsKey = "cpu:stats:" + cpuData.getHostname();

// 更新统计信息
Map<String, Object> stats = new HashMap<>();
stats.put("currentCpuUsage", cpuData.getCpuUsage());
stats.put("currentLoad", cpuData.getLoadAverage1m());
stats.put("cpuCores", cpuData.getCpuCores());
stats.put("lastUpdateTime", System.currentTimeMillis());

redisTemplate.opsForValue().set(statsKey, stats, Duration.ofMinutes(10));

} catch (Exception e) {
log.warn("更新CPU统计信息失败: {}", e.getMessage());
}
}

/**
* 获取实时CPU数据
*/
public CpuMonitorData getRealTimeCpuData(String hostname) {
String cacheKey = "cpu:realtime:" + hostname;
return (CpuMonitorData) redisTemplate.opsForValue().get(cacheKey);
}

/**
* 获取CPU历史数据
*/
public List<CpuMonitorData> getCpuHistoryData(String hostname, Date startTime, Date endTime) {
return cpuMonitorDataMapper.selectByHostnameAndTimeRange(hostname, startTime, endTime);
}

/**
* 获取CPU统计信息
*/
public Map<String, Object> getCpuStatistics(String hostname) {
String statsKey = "cpu:stats:" + hostname;
return (Map<String, Object>) redisTemplate.opsForValue().get(statsKey);
}

/**
* 获取活跃告警
*/
public List<CpuAlertRecord> getActiveAlerts(String hostname) {
return cpuAlertRecordMapper.selectActiveAlertsByHostname(hostname);
}
}

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
/**
* 系统信息采集服务
* 使用OSHI库采集系统信息
*/
@Service
public class SystemInfoService {

private final SystemInfo systemInfo;
private final OperatingSystemMXBean osBean;
private final MemoryMXBean memoryBean;

public SystemInfoService() {
this.systemInfo = new SystemInfo();
this.osBean = ManagementFactory.getOperatingSystemMXBean();
this.memoryBean = ManagementFactory.getMemoryMXBean();
}

/**
* 获取系统信息
*/
public SystemInfo getSystemInfo() {
SystemInfo info = new SystemInfo();

// 设置基本信息
info.setHostname(getHostname());
info.setIp(getLocalIpAddress());
info.setOsName(osBean.getName());
info.setOsVersion(osBean.getVersion());
info.setOsArch(osBean.getArch());

// 设置CPU信息
info.setCpuInfo(getCpuInfo());

// 设置内存信息
info.setMemoryInfo(getMemoryInfo());

// 设置负载信息
info.setLoadAverage(getLoadAverage());

return info;
}

/**
* 获取CPU信息
*/
private CpuInfo getCpuInfo() {
CpuInfo cpuInfo = new CpuInfo();

try {
// 使用OSHI获取CPU信息
HardwareAbstractionLayer hal = systemInfo.getHardware();
CentralProcessor processor = hal.getProcessor();

// 获取CPU使用率
long[] prevTicks = processor.getSystemCpuLoadTicks();
Thread.sleep(1000); // 等待1秒
long[] ticks = processor.getSystemCpuLoadTicks();

// 计算CPU使用率
double cpuUsage = processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100;
cpuInfo.setUsage(cpuUsage);

// 获取详细CPU信息
long[] cpuTicks = processor.getSystemCpuLoadTicks();
long totalTicks = Arrays.stream(cpuTicks).sum();

if (totalTicks > 0) {
cpuInfo.setUser((double) cpuTicks[CentralProcessor.TickType.USER.getIndex()] / totalTicks * 100);
cpuInfo.setSystem((double) cpuTicks[CentralProcessor.TickType.SYSTEM.getIndex()] / totalTicks * 100);
cpuInfo.setIdle((double) cpuTicks[CentralProcessor.TickType.IDLE.getIndex()] / totalTicks * 100);
cpuInfo.setIowait((double) cpuTicks[CentralProcessor.TickType.IOWAIT.getIndex()] / totalTicks * 100);
}

// 设置CPU核心数
cpuInfo.setCores(processor.getLogicalProcessorCount());

// 设置CPU频率
cpuInfo.setFrequency(processor.getMaxFreq());

} catch (Exception e) {
log.error("获取CPU信息失败: {}", e.getMessage(), e);
// 使用备用方法
cpuInfo = getCpuInfoFallback();
}

return cpuInfo;
}

/**
* 获取CPU信息备用方法
*/
private CpuInfo getCpuInfoFallback() {
CpuInfo cpuInfo = new CpuInfo();

try {
// 使用ManagementFactory获取CPU信息
OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();

// 获取系统负载
double systemLoad = osBean.getSystemLoadAverage();
if (systemLoad >= 0) {
cpuInfo.setUsage(systemLoad * 100);
}

// 获取CPU核心数
cpuInfo.setCores(osBean.getAvailableProcessors());

// 设置默认值
cpuInfo.setUser(0.0);
cpuInfo.setSystem(0.0);
cpuInfo.setIdle(100.0);
cpuInfo.setIowait(0.0);
cpuInfo.setFrequency(0L);

} catch (Exception e) {
log.error("获取CPU信息备用方法失败: {}", e.getMessage(), e);
}

return cpuInfo;
}

/**
* 获取内存信息
*/
private MemoryInfo getMemoryInfo() {
MemoryInfo memoryInfo = new MemoryInfo();

try {
// 使用OSHI获取内存信息
HardwareAbstractionLayer hal = systemInfo.getHardware();
GlobalMemory memory = hal.getMemory();

// 设置内存信息
memoryInfo.setTotal(memory.getTotal());
memoryInfo.setAvailable(memory.getAvailable());
memoryInfo.setUsed(memory.getTotal() - memory.getAvailable());
memoryInfo.setUsage((double) memoryInfo.getUsed() / memoryInfo.getTotal() * 100);

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

return memoryInfo;
}

/**
* 获取负载平均值
*/
private LoadAverage getLoadAverage() {
LoadAverage loadAverage = new LoadAverage();

try {
OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();

// 获取负载平均值
double load1m = osBean.getSystemLoadAverage();
if (load1m >= 0) {
loadAverage.setLoad1m(load1m);
// 5分钟和15分钟负载平均值需要额外计算
loadAverage.setLoad5m(load1m * 0.8); // 简化计算
loadAverage.setLoad15m(load1m * 0.6); // 简化计算
}

} catch (Exception e) {
log.error("获取负载平均值失败: {}", e.getMessage(), e);
}

return loadAverage;
}

/**
* 获取主机名
*/
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";
}
}
}

/**
* 系统信息实体类
*/
@Data
public class SystemInfo {
private String hostname; // 主机名
private String ip; // IP地址
private String osName; // 操作系统名称
private String osVersion; // 操作系统版本
private String osArch; // 操作系统架构
private CpuInfo cpuInfo; // CPU信息
private MemoryInfo memoryInfo; // 内存信息
private LoadAverage loadAverage; // 负载平均值
}

/**
* CPU信息实体类
*/
@Data
public class CpuInfo {
private Double usage; // CPU使用率
private Double user; // 用户态CPU使用率
private Double system; // 系统态CPU使用率
private Double idle; // 空闲CPU使用率
private Double iowait; // IO等待CPU使用率
private Integer cores; // CPU核心数
private Long frequency; // CPU频率
}

/**
* 内存信息实体类
*/
@Data
public class MemoryInfo {
private Long total; // 总内存
private Long available; // 可用内存
private Long used; // 已使用内存
private Double usage; // 内存使用率
}

/**
* 负载平均值实体类
*/
@Data
public class LoadAverage {
private Double load1m; // 1分钟负载平均值
private Double load5m; // 5分钟负载平均值
private Double load15m; // 15分钟负载平均值
}

5. CPU性能优化服务

5.1 CPU性能优化服务

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
/**
* CPU性能优化服务
* 提供CPU性能优化和自动调优功能
*/
@Service
public class CpuOptimizationService {

@Autowired
private CpuMonitorService cpuMonitorService;

@Autowired
private ProcessService processService;

@Autowired
private AlertService alertService;

/**
* 自动CPU优化
* 根据CPU使用情况自动进行优化
*/
@Scheduled(fixedRate = 30000) // 每30秒执行一次
public void autoOptimizeCpu() {
try {
String hostname = getHostname();
CpuMonitorData cpuData = cpuMonitorService.getRealTimeCpuData(hostname);

if (cpuData == null) {
return;
}

// 检查CPU使用率
if (cpuData.getCpuUsage() > 90) {
// CPU使用率过高,执行优化策略
executeHighCpuOptimization(cpuData);
} else if (cpuData.getCpuUsage() > 80) {
// CPU使用率较高,执行预防性优化
executePreventiveOptimization(cpuData);
}

} catch (Exception e) {
log.error("自动CPU优化失败: {}", e.getMessage(), e);
}
}

/**
* 执行高CPU使用率优化
*/
private void executeHighCpuOptimization(CpuMonitorData cpuData) {
log.warn("执行高CPU使用率优化: cpuUsage={}%", cpuData.getCpuUsage());

try {
// 1. 查找高CPU使用率进程
List<ProcessInfo> highCpuProcesses = processService.getHighCpuProcesses();

// 2. 分析进程类型
for (ProcessInfo process : highCpuProcesses) {
analyzeAndOptimizeProcess(process);
}

// 3. 调整JVM参数
optimizeJvmParameters();

// 4. 清理系统资源
cleanupSystemResources();

// 5. 发送优化通知
sendOptimizationNotification(cpuData, "HIGH_CPU_OPTIMIZATION");

} catch (Exception e) {
log.error("执行高CPU使用率优化失败: {}", e.getMessage(), e);
}
}

/**
* 执行预防性优化
*/
private void executePreventiveOptimization(CpuMonitorData cpuData) {
log.info("执行预防性CPU优化: cpuUsage={}%", cpuData.getCpuUsage());

try {
// 1. 检查系统负载
if (cpuData.getLoadAverage1m() > cpuData.getCpuCores()) {
// 负载过高,执行负载均衡
executeLoadBalancing();
}

// 2. 优化缓存策略
optimizeCacheStrategy();

// 3. 调整线程池参数
optimizeThreadPoolParameters();

// 4. 发送优化通知
sendOptimizationNotification(cpuData, "PREVENTIVE_OPTIMIZATION");

} catch (Exception e) {
log.error("执行预防性优化失败: {}", e.getMessage(), e);
}
}

/**
* 分析和优化进程
*/
private void analyzeAndOptimizeProcess(ProcessInfo process) {
try {
// 1. 分析进程类型
String processType = analyzeProcessType(process);

// 2. 根据进程类型执行优化
switch (processType) {
case "JAVA_PROCESS":
optimizeJavaProcess(process);
break;
case "DATABASE_PROCESS":
optimizeDatabaseProcess(process);
break;
case "WEB_SERVER":
optimizeWebServerProcess(process);
break;
case "UNKNOWN_PROCESS":
handleUnknownProcess(process);
break;
}

} catch (Exception e) {
log.error("分析和优化进程失败: pid={}, error={}",
process.getPid(), e.getMessage(), e);
}
}

/**
* 分析进程类型
*/
private String analyzeProcessType(ProcessInfo process) {
String command = process.getCommand().toLowerCase();

if (command.contains("java") || command.contains("jvm")) {
return "JAVA_PROCESS";
} else if (command.contains("mysql") || command.contains("postgresql") ||
command.contains("mongodb") || command.contains("redis")) {
return "DATABASE_PROCESS";
} else if (command.contains("nginx") || command.contains("apache") ||
command.contains("tomcat") || command.contains("jetty")) {
return "WEB_SERVER";
} else {
return "UNKNOWN_PROCESS";
}
}

/**
* 优化Java进程
*/
private void optimizeJavaProcess(ProcessInfo process) {
log.info("优化Java进程: pid={}, name={}", process.getPid(), process.getName());

try {
// 1. 检查GC情况
checkGcStatus(process);

// 2. 调整堆内存
adjustHeapMemory(process);

// 3. 优化GC参数
optimizeGcParameters(process);

// 4. 调整线程池
adjustThreadPool(process);

} catch (Exception e) {
log.error("优化Java进程失败: pid={}, error={}",
process.getPid(), e.getMessage(), e);
}
}

/**
* 优化数据库进程
*/
private void optimizeDatabaseProcess(ProcessInfo process) {
log.info("优化数据库进程: pid={}, name={}", process.getPid(), process.getName());

try {
// 1. 检查连接数
checkConnectionCount(process);

// 2. 优化查询缓存
optimizeQueryCache(process);

// 3. 调整缓冲区大小
adjustBufferSize(process);

} catch (Exception e) {
log.error("优化数据库进程失败: pid={}, error={}",
process.getPid(), e.getMessage(), e);
}
}

/**
* 优化Web服务器进程
*/
private void optimizeWebServerProcess(ProcessInfo process) {
log.info("优化Web服务器进程: pid={}, name={}", process.getPid(), process.getName());

try {
// 1. 调整工作进程数
adjustWorkerProcesses(process);

// 2. 优化连接超时
optimizeConnectionTimeout(process);

// 3. 启用压缩
enableCompression(process);

} catch (Exception e) {
log.error("优化Web服务器进程失败: pid={}, error={}",
process.getPid(), e.getMessage(), e);
}
}

/**
* 处理未知进程
*/
private void handleUnknownProcess(ProcessInfo process) {
log.warn("发现未知高CPU使用率进程: pid={}, name={}, cpuUsage={}%",
process.getPid(), process.getName(), process.getCpuUsage());

// 发送告警通知
AlertMessage alert = new AlertMessage();
alert.setType("UNKNOWN_HIGH_CPU_PROCESS");
alert.setLevel("WARNING");
alert.setMessage(String.format("未知进程CPU使用率过高: %s (PID: %d, CPU: %.2f%%)",
process.getName(), process.getPid(), process.getCpuUsage()));
alert.setTimestamp(new Date());

alertService.sendAlert(alert);
}

/**
* 优化JVM参数
*/
private void optimizeJvmParameters() {
log.info("优化JVM参数");

try {
// 1. 检查当前JVM参数
RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
List<String> jvmArgs = runtimeBean.getInputArguments();

// 2. 分析JVM参数
analyzeJvmArguments(jvmArgs);

// 3. 建议优化参数
suggestJvmOptimizations();

} catch (Exception e) {
log.error("优化JVM参数失败: {}", e.getMessage(), e);
}
}

/**
* 分析JVM参数
*/
private void analyzeJvmArguments(List<String> jvmArgs) {
Map<String, String> currentParams = new HashMap<>();

for (String arg : jvmArgs) {
if (arg.startsWith("-X")) {
String[] parts = arg.split("=", 2);
if (parts.length == 2) {
currentParams.put(parts[0], parts[1]);
} else {
currentParams.put(parts[0], "true");
}
}
}

log.info("当前JVM参数: {}", currentParams);
}

/**
* 建议JVM优化
*/
private void suggestJvmOptimizations() {
List<String> suggestions = new ArrayList<>();

// 检查堆内存设置
suggestions.add("建议设置合适的堆内存大小: -Xms2g -Xmx2g");

// 检查GC设置
suggestions.add("建议使用G1垃圾收集器: -XX:+UseG1GC");

// 检查线程设置
suggestions.add("建议设置合适的线程栈大小: -Xss256k");

log.info("JVM优化建议: {}", suggestions);
}

/**
* 清理系统资源
*/
private void cleanupSystemResources() {
log.info("清理系统资源");

try {
// 1. 清理临时文件
cleanupTempFiles();

// 2. 清理日志文件
cleanupLogFiles();

// 3. 清理缓存
cleanupCache();

} catch (Exception e) {
log.error("清理系统资源失败: {}", e.getMessage(), e);
}
}

/**
* 清理临时文件
*/
private void cleanupTempFiles() {
try {
Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
Files.walk(tempDir)
.filter(Files::isRegularFile)
.filter(path -> {
try {
return Files.getLastModifiedTime(path).toInstant()
.isBefore(Instant.now().minus(7, ChronoUnit.DAYS));
} catch (IOException e) {
return false;
}
})
.forEach(path -> {
try {
Files.delete(path);
log.debug("删除临时文件: {}", path);
} catch (IOException e) {
log.warn("删除临时文件失败: {}", path);
}
});
} catch (Exception e) {
log.error("清理临时文件失败: {}", e.getMessage(), e);
}
}

/**
* 清理日志文件
*/
private void cleanupLogFiles() {
// 实现日志文件清理逻辑
log.info("清理日志文件");
}

/**
* 清理缓存
*/
private void cleanupCache() {
// 实现缓存清理逻辑
log.info("清理缓存");
}

/**
* 发送优化通知
*/
private void sendOptimizationNotification(CpuMonitorData cpuData, String optimizationType) {
try {
AlertMessage alert = new AlertMessage();
alert.setType("CPU_OPTIMIZATION");
alert.setLevel("INFO");
alert.setMessage(String.format("CPU优化完成: 类型=%s, CPU使用率=%.2f%%",
optimizationType, cpuData.getCpuUsage()));
alert.setTimestamp(new Date());

alertService.sendAlert(alert);

} catch (Exception e) {
log.error("发送优化通知失败: {}", e.getMessage(), e);
}
}

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

6. 告警服务

6.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
/**
* 告警服务
* 负责发送各种告警通知
*/
@Service
public class AlertService {

@Autowired
private EmailService emailService;

@Autowired
private WebhookService webhookService;

@Autowired
private SmsService smsService;

/**
* 发送CPU告警
*/
public void sendCpuAlert(CpuAlertRecord alertRecord) {
try {
// 1. 创建告警消息
AlertMessage alertMessage = createAlertMessage(alertRecord);

// 2. 发送邮件告警
if (emailService.isEnabled()) {
emailService.sendCpuAlert(alertMessage);
}

// 3. 发送Webhook告警
if (webhookService.isEnabled()) {
webhookService.sendAlert(alertMessage);
}

// 4. 发送短信告警(严重告警)
if ("CRITICAL".equals(alertRecord.getAlertLevel()) && smsService.isEnabled()) {
smsService.sendAlert(alertMessage);
}

log.info("发送CPU告警: hostname={}, level={}",
alertRecord.getHostname(), alertRecord.getAlertLevel());

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

/**
* 发送通用告警
*/
public void sendAlert(AlertMessage alertMessage) {
try {
// 根据告警级别选择发送方式
switch (alertMessage.getLevel()) {
case "CRITICAL":
sendCriticalAlert(alertMessage);
break;
case "WARNING":
sendWarningAlert(alertMessage);
break;
case "INFO":
sendInfoAlert(alertMessage);
break;
}

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

/**
* 发送严重告警
*/
private void sendCriticalAlert(AlertMessage alertMessage) {
// 发送所有类型的通知
emailService.sendAlert(alertMessage);
webhookService.sendAlert(alertMessage);
smsService.sendAlert(alertMessage);
}

/**
* 发送警告告警
*/
private void sendWarningAlert(AlertMessage alertMessage) {
// 发送邮件和Webhook通知
emailService.sendAlert(alertMessage);
webhookService.sendAlert(alertMessage);
}

/**
* 发送信息告警
*/
private void sendInfoAlert(AlertMessage alertMessage) {
// 只发送Webhook通知
webhookService.sendAlert(alertMessage);
}

/**
* 创建告警消息
*/
private AlertMessage createAlertMessage(CpuAlertRecord alertRecord) {
AlertMessage alertMessage = new AlertMessage();
alertMessage.setType(alertRecord.getAlertType());
alertMessage.setLevel(alertRecord.getAlertLevel());
alertMessage.setMessage(alertRecord.getAlertMessage());
alertMessage.setTimestamp(alertRecord.getAlertTime());
alertMessage.setHostname(alertRecord.getHostname());
alertMessage.setIp(alertRecord.getIp());

return alertMessage;
}
}

/**
* 告警消息实体类
*/
@Data
public class AlertMessage {
private String type; // 告警类型
private String level; // 告警级别
private String message; // 告警消息
private Date timestamp; // 告警时间
private String hostname; // 主机名
private String ip; // IP地址
private Map<String, Object> details; // 详细信息
}

7. 总结

本文详细介绍了CPU运维监控与性能优化的完整解决方案,包括:

7.1 核心技术点

  1. CPU监控: 实时监控CPU使用率、负载、核心数等指标
  2. 性能分析: 分析CPU使用趋势、识别性能瓶颈
  3. 自动优化: 根据CPU使用情况自动执行优化策略
  4. 告警通知: 多通道告警通知(邮件、短信、Webhook)
  5. 运维自动化: 自动化的CPU监控和优化流程

7.2 架构优势

  1. 实时监控: 5秒间隔的实时CPU数据采集
  2. 智能告警: 基于阈值的智能告警机制
  3. 自动优化: 自动化的CPU性能优化
  4. 多维度分析: CPU使用率、负载、进程等多维度分析

7.3 最佳实践

  1. 监控策略: 设置合理的监控间隔和告警阈值
  2. 优化策略: 根据进程类型执行针对性优化
  3. 告警策略: 分级告警,避免告警风暴
  4. 自动化: 实现监控和优化的全自动化

通过以上架构设计,可以构建完善的CPU运维监控系统,实现CPU资源的有效管理和性能优化。