在经过五天的学习和资料收集后,终于初步实现了利用sqldependency进行数据库变化监控,signalr进行前后台交互,数据实时更新。下面将源代码贴出进行初步分析:

1.系统整体框架构成:

2.具体代码分析:

1.signalr交互(利用persistence connection)

a.新建web程序

b.引入Signalr(通过nuget包引入)

c.使用persistence connection模式(当然也可以使用Hub模式)

1.新建persistence connection类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.SignalR; public class MyConnection1 : PersistentConnection
{
protected override Task OnConnected(IRequest request, string connectionId)
{
return Connection.Send(connectionId, "Welcome!");
} protected override Task OnReceived(IRequest request, string connectionId, string data)
{
return Connection.Broadcast(data);
}
}

2.新建owin startup路由文件(startup.cs)

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin; [assembly: OwinStartup(typeof(Startup))] public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR<MyConnection1>("/echo");
}
}

3.前台js交互

引入相关js文件,在JavaScript.js中进行编程,与后台signalr服务端交互。

<script src="Scripts/jquery-1.6.4.js"></script>

  <script src="Scripts/jquery.signalR-2.3.0.js"></script>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://img.hcharts.cn/jquery/jquery-1.8.3.min.js"></script>
<script src="https://img.hcharts.cn/highstock/highstock.js"></script>
<script src="https://img.hcharts.cn/highcharts/modules/exporting.js"></script>
<script src="https://img.hcharts.cn/highcharts-plugins/highcharts-zh_CN.js"></script>
<script src="https://img.hcharts.cn/highcharts/themes/grid-light.js"></script>
<script src="Scripts/moment.js"></script>
<title>
Signalr Test
</title> </head>
<body>
<script src="Scripts/jquery-1.6.4.js"></script>
<script src="Scripts/jquery.signalR-2.3.0.js"></script>
<div id="main" style="width: 1500px;height:400px;"></div>
<script src="JavaScript.js"></script>
</body>
</html>

4.编写交互js和后台调度数据

$.connection('/echo')与signalr服务端进行连接,$.receive()接收来自服务端推送。我的思路是当后台接收数据变化时,推送消息给客户端,当$.receive()接收到信息时,直接执行getdata(),刷新数据。

Highcharts.setOptions({
global: {
useUTC: true
}
});
var chart = null;
var names = [];
var getTime8h = new Date('2015-01-01 08:00:00').getTime() - new Date('2015-01-01 00:00:00').getTime();
// Create the chart
$(document).ready(function () {
seriesOptions = [];
chart = new Highcharts.stockChart({ chart: {
renderTo: 'main',
type: 'spline',
},
rangeSelector: {
buttons: [{
type: 'minute',
count: 5,
text: '5分钟',
},
{
type: 'hour',
count: 1,
text: '小时'
}, {
type: 'day',
count: 1,
text: '一天'
}, {
type: 'all',
text: '所有'
}],
inputEnabled: false,
selected: 0,
},
//navigator: {
// adaptToUpdatedData: false,
// series: {
// data: datatim
// }
//},
title: {
text: '曲线分析平台测试'
},
tooltip: {
split: false,
dateTimeLabelFormats: {
millisecond: '%Y-%m-%d<br/> %H:%M:%S',
second: '%Y-%m-%d<br/> %H:%M:%S',
minute: '%Y-%m-%d<br/> %H:%M',
hour: '%Y-%m-%d<br/> %H:%M',
day: '%Y<br/> %m-%d',
week: '%Y<br/> %m-%d',
month: '%Y-%m',
year: '%Y'
},
},
exporting: {
enabled: true, },
//xAxis: {
// type: 'datetimee',
// data: time,
// tickPixelInterval: 150,
// maxZoom: 20 * 1000
//}
xAxis: {
dateTimeLabelFormats: {
millisecond: '%Y-%m-%d<br/> %H:%M:%S',
second: '%Y-%m-%d<br/> %H:%M:%S',
minute: '%Y-%m-%d<br/> %H:%M',
hour: '%Y-%m-%d<br/> %H:%M',
day: '%Y<br/> %m-%d',
week: '%Y<br/> %m-%d',
month: '%Y-%m',
year: '%Y'
},
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'sgrade',
margin: 80
}
},
series: [{
name: 'demo',
data: [],
}]
});
var conn = $.connection('/echo');
conn.start().done(function (data) {
console.log("当前clientID=" + data.id);
});
//接受服务器的推送
conn.received(function (data) {
getdata();
console.log("server返回的数据: " + data);
});
function getdata() {
var datatim = [];
var time = [];
$.ajax({
type: "post",
async: false, //异步请求(同步请求将会锁住浏览器,用户其他操作必须等待请求完成才可以执行)
url: "Default.aspx?method=getdata",
data: {},
dataType: "json", //返回数据形式为json
success: function (data) { data.forEach(function (e, j) {
var a = new Array();
// console.log(e.datetimee);
a.push(Date.parse(e.datetimee) + getTime8h);
a.push(e.Sgrade);
datatim.push(a);
}); console.log(datatim); chart.series[0].setData(datatim); },
})
} })

5.编写后台数据获取不需要改变(参照C#曲线分析平台的制作(三,三层构架+echarts显示)

Default.aspx后台编写

using BLL;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string method = Request.QueryString["method"];
if (!string.IsNullOrEmpty(method))
{
if (method == "getdata")
{
data(); }
}
} public void data()
{
DataTable dt = new DataTable();
dt = UserManage.returntable();
// lists = new List<object>();
// lists = UserManage.returnlist(); object JSONObj = (Object)JsonConvert.SerializeObject(dt);
Response.Write(JSONObj);
// 一定要加,不然前端接收失败
Response.End(); }
}

3.windows服务编写监控sqldependency变化:

先前考虑的是直接使用console后台监控,但考虑到其容易被人误操作给直接关闭,故而寻求更稳定的windows服务。

新建windows服务->编写services.cs文件:

改写网友提供的博客,然后在sqldependency触发变化事件时,添加相关signalr连接和数据发送(以用来触发前端客户端触发getdata())

var connection = new Connection("http://localhost:4454/echo");

connection.Start().Wait();

                connection.Send("hello").Wait();

using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks; namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
string _connStr = @"Server=.;Database=SanCengDemo;Trusted_Connection=True";
public Service1()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{ SqlDependency.Start(_connStr);//传入连接字符串,启动基于数据库的监听
UpdateGrid();
} private void UpdateGrid()
{
string _connStr = @"Server=.;Database=SanCengDemo;Trusted_Connection=True";
using (SqlConnection connection = new SqlConnection(_connStr))
{
//依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[],如果where条件存在datetime类型,就会导致一直触发onChange事件
using (SqlCommand command = new SqlCommand("select Sid,Sgrade,[DateTimee] From [dbo].[Student]", connection))
{
command.CommandType = CommandType.Text;
connection.Open();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); SqlDataReader sdr = command.ExecuteReader();
Console.WriteLine();
while (sdr.Read())
{
Console.WriteLine("Sid:{0}\tSgrade:{1}\tDateTimee:{2}", sdr["Sid"].ToString(), sdr["Sgrade"].ToString(), sdr["DateTimee"].ToString());
}
sdr.Close();
}
}
} private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= dependency_OnChange;
if (e.Info != SqlNotificationInfo.Invalid)
{
var connection = new Connection("http://localhost:4454/echo");
connection.Start().Wait();
connection.Send("hello").Wait();
UpdateGrid();//此处需重复注册<span style="font-family: Arial, Helvetica, sans-serif;">SqlDependency,每次注册只执行一次,SqlDependency.id可用用于验证注册唯一 编号
}
} protected override void OnStop()
{
// this.timer1.Enabled = false;
}
}
}

4.实验结果:

初步达到实验目的,下一步测试稳定性和占用的内存和CPU损耗情况。

C#曲线分析平台的制作(六,Sqldependency+Signalr+windows 服务)的更多相关文章

  1. C#曲线分析平台的制作(四,highcharts+ajax加载后台数据)

    在上一篇博客:C#曲线分析平台的制作(三,三层构架+echarts显示)中已经完成了后台的三层构架的简单搭建,为实现后面的拓展应用开发和review 改写提供了方便.而在曲线分析平台中,往往有要求时间 ...

  2. C#曲线分析平台的制作(一,ajax+json前后台数据传递)

    在最近的项目学习中,需要建立一个实时数据的曲线分析平台,这其中的关键在于前后台数据传递过程的学习,经过一天的前辈资料整理,大概有了一定的思路,现总结如下: 1.利用jquery下ajax函数实现: & ...

  3. C#曲线分析平台的制作(五,Sqldependency+Signalr+windows 服务 学习资料总结)

    在前篇博客中,利用interval()函数,进行ajax轮询初步的实现的对数据的实时显示.但是在工业级别实时显示中,这并非是一种最好的解决方案.随着Html5 websocket的发展,这种全双工的通 ...

  4. C#曲线分析平台的制作(三,三层构架+echarts显示)

    本文依据CSDN另一位网友关于三层构架的简单搭建,基于他的源码进行修改.实现了三层构架合理结构,以及从数据库中传递数值在echarts显示的实验目的. 废话不多说,show me codes: 具体构 ...

  5. C#曲线分析平台的制作(二,echarts前后台数据显示)

    在上一篇博客中,学习了使用javascript和jquery两种方法来进行前后台交互.本篇博客着重利用jquery+echarts来实现从后台取数,从前端echarts中展示. 1.html页面编写: ...

  6. 关于在windows平台下将应用制作成windows服务及服务依赖的感想

    在某些情况下,应用需要部署在windows平台下,单纯的手动点击exe执行文件或java -jar xxx.jar在实际生产环境中不是最佳实践(制作成bat启动文件置于启动项里,服务器启动后,需要人工 ...

  7. Hermes实时检索分析平台

    一.序言 随着TDW的发展,公司在大数据离线分析方面已经具备了行业领先的能力.但是,很多应用场景往往要求在数秒内完成对几亿.几十亿甚至几百上千亿的数据分析,从而达到不影响用户体验的目的.如何能够及时有 ...

  8. 利用R语言打造量化分析平台

    利用R语言打造量化分析平台 具体利用quantmod包实现对股票的量化分析 1.#1.API读取在线行情2.#加载quantmod包3.if(!require(quantmod)){4. instal ...

  9. TOP100summit:【分享实录-WalmartLabs】利用开源大数据技术构建WMX广告效益分析平台

    本篇文章内容来自2016年TOP100summitWalmartLabs实验室广告平台首席工程师.架构师粟迪夫的案例分享. 编辑:Cynthia 粟迪夫:WalmartLabs实验室广告平台首席工程师 ...

随机推荐

  1. vue keep-alive从列表页进入详情页,再返回列表页时,还是之前滚动的位置

    //router.js { path: '/oppo-music', component: () => import('@/views/OppoMusic.vue'), meta: { titl ...

  2. 干货 | LuatOS BSP移植教程,简单到复制粘贴!!!

    LuatOS本着自身的开源特性,可以很轻松的嵌入到很多微处理器和微控制器.今天简要讲下如何移植这套系统,上手比较简单,看完基本就会了. 要想做移植,就要先了解需要移植芯片的SDK,LuatOS依赖于F ...

  3. 手写Spring Config,最终一战,来瞅瞅撒!

    上一篇说到了手写Spring AOP,来进行功能的增强,下面本篇内容主要是手写Spring Config.通过配置的方式来使用Spring 前面内容链接: 我自横刀向天笑,手写Spring IOC容器 ...

  4. UBoot的编译与烧写

    每当我们学习任何编译语言之前,第一节课都是介绍我们要学习的是什么,以及编译语言和工具,最后写一个小程序编译并运行就算入门,也就是所谓的"Hello, world!".这里也不例外, ...

  5. 复习Spring第三课--数据源配置的多种方式

    spring数据源配置可以说分为:spring容器自带连接池.项目中创建连接池.服务器创建连接池三种 一.spring容器自带连接池   Spring本身也提供了一个简单的数据源实现类DriverMa ...

  6. QPainter::begin: Paint device returned engine == 0, type: 1

    开始 使用QPainter画图,需要继承QWidget,重写paintEvent()虚函数,在里面进行绘图. 或者可以考虑绘制到QImage或者QPixmap上面,然后在paintEvent()里面调 ...

  7. flex mx:TabNavigator进行选项卡切换,需要进行交互时。发生Error #1009错误

    当需要进行 mx:TabNavigator选项卡进行切换时,需要进行交互,然后却报了"TypeError: Error #1009: 无法访问空对象引用的属性或方法."错误,产生这 ...

  8. CentOS-Docker搭建远程监控服务器指标

    注:远程监控服务器指标,可查看.CPU.内存.网络信息等,搭建依赖Docker环境,可参考:yum安装Docker环境 服务端:Grafana(可视化展示) + Prometheus(数据源,配置客户 ...

  9. C#/VB.NET 设置PDF跨页表格重复显示表头行

    在创建表格时,如果表格内容出现跨页显示的时候,默认情况下该表格的表头不会在下一页显示,在阅读体验上不是很好.下面分享一个方法如何在表格跨页时显示表格的表头内容,在C#中只需要简单使用方法grid.Re ...

  10. IDEA连接数据库出现报错

    解决办法 jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useJDBCComplia ...