美文网首页后端
hangfire的安装和简单使用

hangfire的安装和简单使用

作者: Daniel_adu | 来源:发表于2017-05-08 19:30 被阅读1693次

    hangfire

    hangfire是一个backgroundjob的开源库,使用这个库有几个好处
    (1)省去了创建线程的过程,线程管理,任务队列都已经维护好
    (2)有重试机制,10次重试
    (3)有网页监控机制,能看到正在运行哪些任务,哪些任务已经完成

    hangfire在asp.net和adp.net core中hangfire的配置和使用是不一样的,在asp.net中:

    在asp.net中:

    首先安装hangfire
    PM> Install-Package Hangfier

    再安装OWIN,这个是能在asp.net中使用startup的,
    装完后导入
    using Hangfire;
    然后

    public void Configuration(IAppBuilder app)
    {
        GlobalConfiguration.Configuration.UseSqlServerStorage("<connection string or its name>");
     
        app.UseHangfireDashboard();
        app.UseHangfireServer();
    }
    

    Hangfire是默认只能在local查看进度的,要想放开权限,需要这样做:

    public void Configuration(IAppBuilder app)
            {
                GlobalConfiguration.Configuration
                    .UseSqlServerStorage(@"connectstring");
                app.UseHangfireDashboard("/hangfire", new DashboardOptions
                {               
                    AuthorizationFilters = new[] { new MyRestrictiveAuthorizationFilter() }
                });
                app.UseHangfireServer();
            }
    

    MyRestrictiveAuthorizationFilter()代码:

    using Hangfire.Dashboard;
    using Microsoft.Owin;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
     
    namespace taskserver
    {
        public class MyRestrictiveAuthorizationFilter : IAuthorizationFilter
        {
            public bool Authorize(IDictionary<string, object> owinEnvironment)
            {
                // In case you need an OWIN context, use the next line,
                // `OwinContext` class is the part of the `Microsoft.Owin` package.
                var context = new OwinContext(owinEnvironment);
     
                // Allow all authenticated users to see the Dashboard (potentially dangerous).
                return true;
            }
        }
    }
    

    就可以远程访问url/hangfire了。

    asp.net core中安装hangfire:

    asp.net core中无处不在的依赖注入(IOC)机制,因此需要和IOC进行配合
    一样,先安装Hangfire
    然后再startup中:
    ConfigureServices方法下:

    services.AddHangfire(x => x.UseSqlServerStorage("connectiionString"));
    services.AddSingleton<IJobService, JobService>();
    

    记住这个IjobService和JobService,接下来要创建的,这里是进行注册

    configure方法中

    app.UseHangfireServer();
    app.UseHangfireDashboard();
    

    当然,如果要配置远程权限,和前面的一样。
    接下来就是编写JobService了。
    这个很简单,使用过asp.net core的都知道,在IJobService中写接口,JobService中继承接口实现方法,别忘了在startUp中注册服务。

    两种环境下的配置讲完了,接下来就该讲如何使用了。
    使用很简单,一般的如果只需要任务执行一次,这样就行:

    BackgroundJob.Enqueue(() => Console.WriteLine("Simple!"));
    

    如果是运行方法,则

    BackgroundJob.Enqueue<IJobService>(x=>x.fun());
    

    注意:IJobService一定要是接口,不是继承这个接口的具体类。
    foo就是想要执行的方法,这个方法会在后台添加到任务队列中,队列会开线程处理这个任务队列,轮到自己的时候就会处理啦。处理完就会扔了。

    相关文章

      网友评论

        本文标题:hangfire的安装和简单使用

        本文链接:https://www.haomeiwen.com/subject/mvrvtxtx.html