Echart+signalR实现实时检测服务器CPU状态
1.前端代码
<h2>CPU使用率</h2>
<div id="mychart" style="width:600px;height:300px;"></div>
@section scripts{
<script src="~/Scripts/Echart/echarts.js"></script>
<script src="~/Scripts/Echart/macarons.js"></script>
<script src="~/Scripts/jquery.signalR-2.3.0.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
///下面的代码声明对中心代理的引用。
var chat = $.connection.cpuHub;
$.connection.hub.start();
$(function () {
var time=[]
var myChart = echarts.init(document.getElementById('mychart'), "macarons");
var data = [];
function addData(shift) {
if (shift) {
data.shift();
time.shift();
console.log("data 数据后的长度:" + data.length);
console.log("time 数据后的长度:" + time.length);
}
}
//接受服务端数据
chat.client.addNewMessageToPage = function (mes) {
time.push(getTime(new Date()));
data.push(mes);
};
option = {
title: {
text: 'cpu占用率'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
toolbox: {//平铺、折叠、生成png图片
show: true,
feature: {
dataView: { readOnly: false },
magicType: { show: true, type: ['stack', 'tiled', 'line', 'bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
xAxis: {
type: 'category',
boundaryGap: false,
splitLine: {
show: true,//是否显示网格线
},
name:"时间"
},
yAxis: {
boundaryGap: [0, '50%'],
type: 'value',
axisLabel: {
formatter: '{value}'
},
name:"单位(%)",
splitLine: {
show: true,//是否显示网格线
},
max:100
},
series: [
{
name: 'CPU',
type: 'line',
smooth: true,
symbol: 'none',
stack: 'a',
data: data
}
]
};
myChart.setOption(option);
setInterval(function () {
addData(true)
console.log("data 数据前的长度:" + data.length);
console.log("time 数据前的长度:" + time.length);
myChart.setOption({
xAxis: {
data: time,
},
series: [{
name: 'CPU',
data: data
}]
});
}, 1500);
})
function getTime(date) {
var Hours = date.getHours();//获取当前小时数(0-23)
var Minutes = date.getMinutes(); //获取当前分钟数(0-59)
var Seconds = date.getSeconds();//获取当前秒数(0-59)
var Milliseconds = date.getMilliseconds();//获取当前毫秒数(0-999)
return Hours + ":" + Minutes + ":" + Seconds
}
</script>}
2.后台代码
public ActionResult Index()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(Send);
timer.Interval = 1000;
timer.Enabled = true;
timer.Start();
return View();
}
public void Send(object sender, System.Timers.ElapsedEventArgs e)
{
Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<CpuHub>().Clients.All.addNewMessageToPage(s.CpuLoad);//向客户端推送占用率
}
3.处理消息
[HubName("cpuHub")]
public class CpuHub : Hub
{
public void Send(string meesges)
{
Clients.All.addNewMessageToPage(meesges);
}
}
4.在MVC中Startup.cs注册 SignalR
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
//注册SignalR
app.MapSignalR();
}
}
附上效果图
缺陷:
1.存在x轴最后一个时间显示不出来(数据量和X轴长度是一样的),
2.还需优化的地方,进出不成比列(进大于出),时间长了,数据量累计很多
分享大家,有需要的朋友可以参考下,对以上不足的两点,希望大牛指点下,