服务器管理系统可视化监控有很多成熟的框架可以选择,我们用过 zabbix , 功能是很多的,但是我们有一些项目只需要很简单的性能监控,用这种成熟框架就有点大材小用了,笔者这里尝试一个简化的方式。
一. 基本结构

- 服务端有一个 agent 应用,不断的轮询发送实时的系统数据,比如 cpu、memory等。以 mqtt 的方式推送到 MQTT Broker.
- 这个 borker 可以用Apache Apollo或EMQ X.
- 网页端就是订阅 mqtt 的消息,然后实时绘制折线图
二. 服务端实现
这里主要使用 sigar 来获取系统相关信息,sigar 在不同的操作系统下需要拷贝对应的 dll 或 so 文件,所以我们封装了一个d1.framework.osinfo库来简化操作,拷贝这些文件都是自动的,相关代码参考Git。连接 mqtt borker 并发布消息调用的是自封装的 d1.framework.mqttclient 库,代码参考 Git 。所以最后的主要代码非常少:
@Scheduled(cron = "0/10 * * * * ?") //10秒一次
public void task() {
//do something
try {
OsInfo info = osInfo.getOsInfo();
mqttService.publish("cpu", info.getFreeCpu());
mqttService.publish("memory", info.getFreeMemory());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("又过了10秒了......");
}
三. 网页端
网页端只是用 IBM 提供的 paho-mqtt js库来订阅 mqtt 消息,然后使用 echarts 来画动态曲线图,代码也很简单。
function initChart(chart, name, xDatas, yDatas) {
// 指定图表的配置项和数据
var option = {
title: {
text: name+"空闲%"
},
tooltip: {},
legend: {
data: [name]
},
xAxis: {
data: xDatas
},
yAxis: {},
series: [{
name: '空闲',
type: 'line',
data: yDatas
}]
};
chart.setOption(option)
return option;
}
//
function initMQTT() {
// Create a client instance
var client = new Paho.Client("这里填broker的地址", 8083, "/mqtt", getRandomString());
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({
userName: "user2",
password: "password2",
onSuccess: onConnect,
onFailure: onFailure
});
// called when the client failed to connect
function onFailure(error) {
console.log("onFailure:" + JSON.stringify(error));
}
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("cpu");
client.subscribe("memory");
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:" + JSON.stringify(message));
if (message.payloadString) {
var temp = message.payloadString;
if ("cpu" == message.topic) {
if(yDatasCPU.length>100)//不能无限增长,只保留最新100条
yDatasCPU.shift();
yDatasCPU.push(Number.parseFloat(temp.substring(0, temp.length - 1)));
if(xDatasCPU.length>100)
xDatasCPU.shift();
xDatasCPU.push(getNow());
cpuChart.setOption(cpuOption);
} else if ("memory" == message.topic) {
if(xDatasMemory.length>100)
xDatasMemory.shift();
xDatasMemory.push(getNow());
if(yDatasMemory.length>100)
yDatasMemory.shift();
yDatasMemory.push(Number.parseFloat(temp.substring(0, temp.length - 1)));
memoryChart.setOption(memoryOption);
}
}
}
}
只是一个示例,所以最后的效果图比较简陋,每10秒会接受到推送过来的 cpu 和 memory 空闲率,动态显示出来,最多显示最近100条数据。

所有源码参考 Git
网友评论