zoukankan      html  css  js  c++  java
  • 【转载】在 ASP.NET Web API 项目中使用 Hangfire 实现后台任务处理

    原文地址:http://www.cnblogs.com/chenxizhang/p/4740921.html

    当前项目中有这样一个需求:由前端用户的一个操作,需要触发到不同设备的消息推送。由于推送这个具体功能,我们采用了第三方的服务。而这个服务调用有时候可能会有延时,为此,我们希望将消息推送与用户前端操作实现异步执行,就是希望在后台自动执行,不阻塞前端用户的操作,而且最好能实现失败重试等功能。

    经过一些研究比较,我们发现使用Hangfire这个组件可以较好地实现这个需求。为了给大家做一个演示,我这里简化了代码,做一个范例程序。

    我在这里不准备详细介绍Hangfire的基本用法,有兴趣的同学们可以参考官方网站 http://hangfire.io/  和文档 http://docs.hangfire.io/en/latest/ 

    imageimage

    第一步:创建ASP.NET Web API项目

    imageimage

    第二步:安装必要的nuget package

    打开Nuget Package Manager Console

    image

    首先安装Hangfire组件(Core,MemoryStorage),注意,因为后者是依赖前者的,所以我们只需要运行下面的命令即可

    Install-Package Hangfire.MemoryStorage

    image

    Storage就是存储的意思,Hangfire的后台任务是需要一个地方保存起来,它默认支持SQL Server Storage和MemoryStorage。采用MemoryStorage无疑是最简单的(不需要有任何外部的依赖)。当然,最大的问题就是,因为是放在内存中的,万一网站出现问题重启,那么没有执行完的任务是会消失的。

    如果要使用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 

    Install-Package Microsoft.Owin.Host.SystemWeb

    image

    第三步:添加Owin Startup Class

    image

    修改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();
    
            }
        }
    }

       

    第四步:实现一个简单的Web API,启动后台任务

    image

    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来模拟客户端调用

    image

    我们可以很容易地发起大量的请求,例如下面这样

    image

    很快就在Dashboard中看到任务状态(有1000个任务)

    image

    但是很快(不到1秒钟的时间),这些任务就全部处理完了

    image

    我们可以在Windows事件日志中看到消息

    image

    以上就是我的简单演示例子。当然,如果还想要实现失败重试,或者更加有意思的一些功能(例如定时发送),可以继续参考官方文档。

    这个范例代码可以通过这里下载  http://files.cnblogs.com/files/chenxizhang/WebApplicationWebApiHangfireSample.zip

  • 相关阅读:
    LeetCode 81 Search in Rotated Sorted Array II(循环有序数组中的查找问题)
    LeetCode 80 Remove Duplicates from Sorted Array II(移除数组中出现两次以上的元素)
    LeetCode 79 Word Search(单词查找)
    LeetCode 78 Subsets (所有子集)
    LeetCode 77 Combinations(排列组合)
    LeetCode 50 Pow(x, n) (实现幂运算)
    LeetCode 49 Group Anagrams(字符串分组)
    LeetCode 48 Rotate Image(2D图像旋转问题)
    LeetCode 47 Permutations II(全排列)
    LeetCode 46 Permutations(全排列问题)
  • 原文地址:https://www.cnblogs.com/ztpark/p/7685150.html
Copyright © 2011-2022 走看看