Hangfire 入门 (使用MySQL存储)

 最近公司的项目要求每小时计算数据并生成报告,使用的Hangfire来实现。git

以前对Hangfire并不了解,因此学习并记录下来,但愿对你们也有帮助。github

环境:数据库

.NET Framework 4.7.2apache

Hangfire.Core 1.7.12app

Hangfire.AspNet 0.2.0框架

Hangfire.MySqlStorage 2.0.3ide

 

这篇文章主要根据官网的内网作一个基础入门,实现最基础的功能。学习

搭建基础框架ui

首先,我建立了一个Web API项目,而后添加Startup类(由于我要使用Hangfire的Dashboard,因此使用Startup类进行配置)。spa

 

 

 

由于我使用的是MySQL数据库(使用SQL Server能够去看官网的例子),使用NuGet添加:

Install-Package Hangfire.MySqlStorage

能够去GitHub查看这个包的说明:Hangfire MySql Storage

 将官网的实例代码复制到Startup类中,并修改了数据存储的配置以下:

public class Startup
{
    private IEnumerable<IDisposable> GetHangfireServers()
    {
        GlobalConfiguration.Configuration
            .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
            .UseStorage(new MySqlStorage("server=127.0.0.1;user id=root;password=111111;Database=hangfiretest;pooling=true;charset=utf8;Allow User Variables=True;", new MySqlStorageOptions
            {
                    //CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                    //SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                    //QueuePollInterval = TimeSpan.Zero,
                    //UseRecommendedIsolationLevel = true,
                    //DisableGlobalLocks = true
            }));

        yield return new BackgroundJobServer();
    }

    public void Configuration(IAppBuilder app)
    {
        app.UseHangfireAspNet(GetHangfireServers);
        app.UseHangfireDashboard();

        // Let's also create a sample background job
        BackgroundJob.Enqueue(() => Debug.WriteLine("Hello world from Hangfire!"));

        // ...other configuration logic
    }
}

说明:

  • Github上面也提示咱们链接字符串要设置容许用户变量,否则你就要收到一个异常了。

    There must be Allow User Variables set to true in the connection string. For example: 

    server=127.0.0.1;uid=root;pwd=root;database={0};Allow User Variables=True

    

  •  MySQL的MySqlStorageOptions选项和SQLServer不一样,这里也不清楚这些配置的做用,先所有注释掉了,之后再研究。

 

这时候就能够运行了 ,成功后能够看获得咱们建的空数据库里面已经有自动生成的表了,而且在输出窗口中能够看到任务执行输出的:

Hello world from Hangfire!

在启动的页面地址后面加上  /hangfire,就能够看到Dashboard页面。

 

添加日志功能

在遇到任务失败的时候日志能帮助咱们更好的查找问题。

Hangfire支持一下日志框架(而且能够自动识别项目中的引用,为咱们记录日志):

  1. Serilog
  2. NLog
  3. Log4Net
  4. EntLib Logging
  5. Loupe
  6. Elmah

若是项目中引用了多个日志框架,日志可能会失败,你可使用下面的代码来配置想使用的日志框架

GlobalConfiguration.Configuration
    .UseSerilogLogProvider()
    .UseNLogLogProvider()
    .UseLog4NetLogProvider()
    .UseEntLibLogProvider()
    .UseLoupeLogProvider()
    .UseElmahLogProvider();

我用了NLog,这里为了让其余同事更清楚我配置了日志功能,因此尽快Hangfire能够自动识别,我仍是把这一句加上了。

 

 而后我无情的发现日志没有生成,忘记了NLog的配置文件,添加上就行了。

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="true"
      internalLogLevel="Debug" internalLogFile="c:\temp\nlog-internal.log">
  <!--throwExceptions 打印出Nlog的内部错误-->

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="myvar" value="myvalue"/>

  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <targets>

    <!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->

    <!--
    Write events to a file with the date in the filename.
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
    <!--文件-->
    <target name="fileLog" xsi:type="File"  fileName="${basedir}/logs/${date:format=yyyyMM}/${shortdate}.log" layout="${longdate} ${logger} ${level:uppercase=true} ${message}   ${exception:format=ToString}" />
  
  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
    <logger name="*" minlevel="Info" writeTo="fileLog" />
 
  </rules>
</nlog>

日志成功生成