在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引用Hangfire和Hangfire.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的面板一摸一样了??
总结以上是内存溢出为你收集整理的在.netcore webapi项目中使用后台任务工具Hangfire全部内容,希望文章能够帮你解决在.netcore webapi项目中使用后台任务工具Hangfire所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)