hangfire 适配 sqlite(litedb) 运行环境 .net core 3.1

657 阅读1分钟

hangfire 适配 litedb的原因.

  • 1 官方已经多年不更新sqlite, 而且useSqliteServer()会有诸多bug, 比如一秒五次,运行次数是乱来的, 定期任务也是乱来的. mysql, mssql则不会有此问题.
  • 2 替代方案可以选择mysql, mssql这些, 但我更懒,我就希望绿色,不需要安装, 所以只剩下sqlite 和 litedb这类选择. 由于原因1,最终选择了litedb

第一步, 引入包

image.png

第二步, 配置数据库

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "Database": "./hf0330.db"
  },
  "AllowedHosts": "*"
}

第三步, 引用配置文件

private IConfiguration Configuration { get; }

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

第四步, 配置hangfire

// This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
    // 配置hangfire
    services.AddHangfire(config =>
    {
        config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            .UseSimpleAssemblyNameTypeSerializer()
            .UseDefaultTypeSerializer()
            .UseLiteDbStorage(Configuration[key: "ConnectionStrings:Database"]);
    });

    //services.AddHangfire(t => t.UseLiteDbStorage(Configuration[key: "ConnectionStrings:Database"]));

    //这里很重要, 配置hangfire服务器
    services.AddHangfireServer();
}

第五步,配置启动管道

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IBackgroundJobClient backgroundJobClient, IRecurringJobManager recurringJobManager)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/", async context =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    });

    //启动Dashboard
    app.UseHangfireDashboard();

    //单次job, 只运行一次
    backgroundJobClient.Enqueue(() => Console.WriteLine("hello hang fire job!"));

    //循环job, 每分钟执行一次
    recurringJobManager.AddOrUpdate(
        "run every minutes",
        () => Console.WriteLine("hello recurring job!"),
        "* * * * *"
    );
}

第六步,查看运行结果

  • 1 console

image.png

  • 2 Dashboard, 神器,你懂的!

image.png

最后,给白嫖党们献上福利, 当然是源码了.

gitee.com/zero530/han…