龙空技术网

Hangfire之Mysql 版本

躺平攻城狮 18

前言:

当前各位老铁们对“firedacmysql”可能比较看重,兄弟们都需要学习一些“firedacmysql”的相关文章。那么小编也在网摘上搜集了一些有关“firedacmysql””的相关资讯,希望你们能喜欢,各位老铁们一起来了解一下吧!

上一篇已讲到:Hangfire之Mssql版本,今天说说下篇Mysql版

首先需要引用包:

这次需要引用4个包

先在appsettings.json配置文件中加入节点:

  "HangFire": {      "DbConnection": "server=127.0.0.1;port=3306;database=hangfire;user=root;password=123;AllowUserVariables=True;",       "LoginPath": "/services/index",  //服务平台地址       "User": "admin",  //用户名        "Pwd": "123456"  //密码  },

在Program.cs文件中注入服务:

//注入Hangfire服务builder.Services.AddHangfireSetup();//防止中文乱码 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN");//注入Jobapp.UseHangfireMiddleware();

注入时实现需实现中间类:AddHangfireSetup 和 UseHangfireMiddleware

  /// <summary>    /// 注入hangfire,并配置是否初始化数据库    /// </summary>    public static class HangfireSetup    {        public static void AddHangfireSetup(this IServiceCollection services)        {            if (services == null) throw new ArgumentNullException(nameof(services));            if (services == null) throw new ArgumentNullException(nameof(services));            string dbConnection = AppSettings.GetSection("HangFire:DbConnection");            services.AddHangfire(configuration => configuration                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)//此方法 只初次创建数据库使用即可                .UseSimpleAssemblyNameTypeSerializer()                .UseRecommendedSerializerSettings()                .UseStorage(new MySqlStorage(dbConnection, new MySqlStorageOptions                {                    TransactionIsolationLevel =                        (IsolationLevel?)System.Data.IsolationLevel.ReadCommitted, //事务隔离级别。默认是读取已提交                    QueuePollInterval = TimeSpan.FromSeconds(15), //- 作业队列轮询间隔。默认值为15秒。                    JobExpirationCheckInterval = TimeSpan.FromHours(1),                    CountersAggregateInterval = TimeSpan.FromMinutes(5),                    PrepareSchemaIfNecessary = false, // 如果设置为true,则创建数据库表,需要提前手动创建库。默认是true                    DashboardJobListLimit = 50000,                    TransactionTimeout = TimeSpan.FromMinutes(1),                    TablesPrefix = "Hangfire"                })));            services.AddHangfireServer();        }    }
/// <summary> /// 配置面板以及注入job /// </summary> public static class HangfireMiddleware    {        public static void UseHangfireMiddleware(this IApplicationBuilder app)        {            if (app == null) throw new ArgumentNullException(nameof(app));            //配置服务            app.UseHangfireServer(ConfigureOptions());             //配置面板               app.UseHangfireDashboard(AppSettings.GetSection("HangFire:LoginPath"), Authorization());             //初始化Interval            IntervalService.Create(app.ApplicationServices);        }        /// <summary>        ///     配置账号模板信息        /// </summary>        /// <returns></returns>        public static DashboardOptions Authorization()        {            var filter = new BasicAuthAuthorizationFilter(                new BasicAuthAuthorizationFilterOptions                {                    SslRedirect = false,                    RequireSsl = false,                    LoginCaseSensitive = false,                    Users = new[]                    {                        new BasicAuthAuthorizationUser                        {                            Login = AppSettings.GetSection("HangFire:User"),                             PasswordClear = AppSettings.GetSection("HangFire:Pwd")                         }                    }                });            return new DashboardOptions            {                Authorization = new[] { filter }            };        }        /// <summary>        /// 配置        /// </summary>        /// <returns></returns>        public static BackgroundJobServerOptions ConfigureOptions()        {            return new()            {                WorkerCount = Environment.ProcessorCount * 5, //并发任务                ServerName = "定时调度服务" //代表服务名称            };        }    }

其中的:

AppSettings 是读取配置文件的公共基类

IntervalService 是初始化主线程基类,之前mssql篇也介绍过

public class IntervalService    {        /// <summary>        /// 初始化任务创建        /// </summary>        /// <param name="provider"></param>        public static void Create(IServiceProvider provider)        {            IntervalService service = (IntervalService)FormatterServices.GetUninitializedObject(typeof(IntervalService));            service.Start();        }        /// <summary>        /// 主线程服务        /// </summary>        public void Start()        {            #region 每天凌晨五点执行            RecurringJob.AddOrUpdate("xxx服务", () => 实现方法, "0 0 5 * * ?", TimeZoneInfo.Local);            #endregion        }    }

时间配置规则为corn表达式,在Hangfire之Mssql版本此文中已经介绍,需要的小伙伴自行查看。

AppSettings类的实现

/// <summary>    /// appsettings.json配置节点    /// </summary>    public class AppSettings    {        public static IConfiguration configuration { get; set; }        static AppSettings()        {            configuration = new ConfigurationBuilder()            .SetBasePath(Directory.GetCurrentDirectory())            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })            .Build();        }        /// <summary>        /// 获取配置文件中的节点值        /// </summary>        /// <param name="sectionAndkeyName">如:AppSetting:xxx:xxx</param>        /// <returns></returns>        public static string GetSection(string sectionAndkeyName)        {            return configuration[$"{sectionAndkeyName}"];        }    }

至此调度服务就搭好了,可以运行看看效果,进入路径为:/services/hangfire,请注意避坑时区问题。

标签: #firedacmysql #查看 mysql版本