加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

在.netcore webapi项目中使用后台任务工具Hangfire

发布时间:2020-12-12 14:16:34 所属栏目:MsSql教程 来源:网络整理
导读:? 安装Hangfire 在webapi项目中通过nuget安装Hangfire.Core,Hangfire.SqlServer,Hangfire.AspNetCore,截止到目前的最新版本是1.7.6。 ? 使用MSSQL数据库 可以创建一个新的数据库,或者使用现有数据库。 CREATE DATABASE [ HangfireTest ] GO ? ?设置appse

?

安装Hangfire

  在webapi项目中通过nuget安装Hangfire.Core,Hangfire.SqlServer,Hangfire.AspNetCore,截止到目前的最新版本是1.7.6。

?

使用MSSQL数据库

  可以创建一个新的数据库,或者使用现有数据库。

CREATE DATABASE [HangfireTest]
GO

?

?设置appsettings.json

{
  "ConnectionStrings": {
    "Hangfire": "Server=.;Database=mssqllocaldb;Integrated Security=SSPI;"
  },"Logging": {
    "LogLevel": {
      "Default": "Warning","Hangfire": "Information"
    }
  },"AllowedHosts": "*"
}

?

注册hangfire服务

  在startup.cs引用HangfireHangfire.SqlServer,然后注册hangfire服务。

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // 注册Hangfire服务
    services.AddHangfire(configuration => configuration
        .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
        .UseSimpleAssemblyNameTypeSerializer()
        .UseRecommendedSerializerSettings()
        .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"),new SqlServerStorageOptions
        {
            CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),QueuePollInterval = TimeSpan.Zero,UseRecommendedIsolationLevel = true,UsePageLocksOnDequeue = true,DisableGlobalLocks = true
        }));

    services.AddHangfireServer();

    services.AddMvc();
}

?

  修改configure方法

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,IBackgroundJobClient backgroundJobs,IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHangfireDashboard();
    backgroundJobs.Enqueue(() => Console.WriteLine("hello from hangfire"));

    app.UseHttpsRedirection();
    app.UseMvc();
}

?

启动项目

  可以看到数据库中自动创建了几张表。

  在项目地址后面加上/hangfire进入hangfire任务面板,这个面板可以说和CAP的面板一摸一样了??

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读