当前项目中有这样一个需求:由前端用户的一个操做,须要触发到不一样设备的消息推送。因为推送这个具体功能,咱们采用了第三方的服务。而这个服务调用有时候可能会有延时,为此,咱们但愿将消息推送与用户前端操做实现异步执行,就是但愿在后台自动执行,不阻塞前端用户的操做,并且最好能实现失败重试等功能。css
通过一些研究比较,咱们发现使用Hangfire这个组件能够较好地实现这个需求。为了给你们作一个演示,我这里简化了代码,作一个范例程序。html
我在这里不许备详细介绍Hangfire的基本用法,有兴趣的同窗们能够参考官方网站 http://hangfire.io/ 和文档 http://docs.hangfire.io/en/latest/ 前端
打开Nuget Package Manager Consolesql
首先安装Hangfire组件(Core,MemoryStorage),注意,由于后者是依赖前者的,因此咱们只须要运行下面的命令便可app
Storage就是存储的意思,Hangfire的后台任务是须要一个地方保存起来,它默认支持SQL Server Storage和MemoryStorage。采用MemoryStorage无疑是最简单的(不须要有任何外部的依赖)。固然,最大的问题就是,由于是放在内存中的,万一网站出现问题重启,那么没有执行完的任务是会消失的。asp.net
若是要使用SQL Server的话,能够参考 http://docs.hangfire.io/en/latest/configuration/using-sql-server.html ,甚至还能够结合MSMQ来提升可用性 http://docs.hangfire.io/en/latest/configuration/using-sql-server-with-msmq.html 异步
接下来为当前项目启用Owin的支持。关于什么是OWin,我这里也不许备多作说明,有兴趣的同窗能够参考 : http://www.cnblogs.com/dudu/p/what-is-owin.html 和 http://owin.org/ 还有 http://www.asp.net/aspnet/overview/owin-and-katana/an-overview-of-project-katana 测试
修改Startup.cs为下面这样的代码网站
using Hangfire; using Hangfire.MemoryStorage; using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(WebApplicationWebApiHangfireSample.Startup))] namespace WebApplicationWebApiHangfireSample { /// <summary> /// 演示Hangfire的配置 /// 做者:陈希章 /// </summary> public class Startup { public void Configuration(IAppBuilder app) { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888 //指定Hangfire使用内存存储后台任务信息 GlobalConfiguration.Configuration.UseMemoryStorage(); //启用HangfireServer这个中间件(它会自动释放) app.UseHangfireServer(); //启用Hangfire的仪表盘(能够看到任务的状态,进度等信息) app.UseHangfireDashboard(); } } }
using Hangfire; using System; using System.Diagnostics; using System.Web.Http; namespace WebApplicationWebApiHangfireSample.Controllers { /// <summary> /// 用来公开给前端用户调用的API /// 做者:陈希章 /// </summary> public class MessageController : ApiController { /// <summary> /// 这个是用来发送消息的静态方法 /// </summary> /// <param name="message"></param> public static void Send(string message) { EventLog.WriteEntry("EventSystem", string.Format("这是由Hangfire后台任务发送的消息:{0},时间为:{1}", message, DateTime.Now)); } public IHttpActionResult Post(string content) { //这里能够作一些业务判断或操做 //而后须要推送的时候,调用下面的方法便可 BackgroundJob.Enqueue(() => Send(content)); //最后返回(这里是当即返回,不会阻塞) return Ok(); } } }
我使用Fiddler来模拟客户端调用ui
咱们能够很容易地发起大量的请求,例以下面这样
很快就在Dashboard中看到任务状态(有1000个任务)
可是很快(不到1秒钟的时间),这些任务就所有处理完了
咱们能够在Windows事件日志中看到消息
以上就是个人简单演示例子。固然,若是还想要实现失败重试,或者更加有意思的一些功能(例如定时发送),能够继续参考官方文档。
这个范例代码能够经过这里下载 http://files.cnblogs.com/files/chenxizhang/WebApplicationWebApiHangfireSample.zip