Exemple #1
0
        //設定hangfire
        void SetUpHangfire(IServiceCollection services)
        {
            string connstr = null;

            connstr = Configuration.GetConnectionString("HangfireConnection");
            Log.Information("設定Hangfire連線=" + connstr);
            //Hangfire的參數設定
            MySqlStorageOptions mySqlStorageOptions = new MySqlStorageOptions
            {
                TransactionIsolationLevel  = IsolationLevel.ReadCommitted,
                QueuePollInterval          = TimeSpan.FromSeconds(15),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval  = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary   = true,
                DashboardJobListLimit      = 50000,
                TransactionTimeout         = TimeSpan.FromMinutes(1),
            };

            //services.AddHangfire(options => options
            //       .UseStorage(new MySqlStorage(connstr, mySqlStorageOptions))
            //       .UseColouredConsoleLogProvider());
            services.AddHangfire(options => options
                                 .UseStorage(new MySqlStorage(connstr, mySqlStorageOptions))
                                 );
            //services.AddHangfire(config =>
            //    config.UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection")));
        }
Exemple #2
0
        public MySqlMonitoringApiTests()
        {
            _connection = new MySqlConnection(ConnectionUtils.GetConnectionString());
            _connection.Open();

            var persistentJobQueueMonitoringApiMock = new Mock <IPersistentJobQueueMonitoringApi>();

            persistentJobQueueMonitoringApiMock.Setup(m => m.GetQueues()).Returns(new[] { "default" });

            var defaultProviderMock = new Mock <IPersistentJobQueueProvider>();

            defaultProviderMock.Setup(m => m.GetJobQueueMonitoringApi())
            .Returns(persistentJobQueueMonitoringApiMock.Object);

            var storageOptions = new MySqlStorageOptions
            {
                DashboardJobListLimit = _jobListLimit
            };
            var mySqlStorageMock = new Mock <MySqlStorage>(_connection, storageOptions);

            mySqlStorageMock
            .Setup(m => m.QueueProviders)
            .Returns(new PersistentJobQueueProviderCollection(defaultProviderMock.Object));

            _storage = mySqlStorageMock.Object;
            _sut     = new MySqlMonitoringApi(_storage, storageOptions);
        }
Exemple #3
0
        private void StartHangfire()
        {
            var options =
                new MySqlStorageOptions
            {
                TransactionIsolationLevel  = IsolationLevel.ReadCommitted,
                QueuePollInterval          = TimeSpan.FromSeconds(15),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval  = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary   = true,
                DashboardJobListLimit      = 50000,
                TransactionTimeout         = TimeSpan.FromMinutes(1),
                TablesPrefix = "Hangfire"
            };
            var connectionString = "server=127.0.0.1;uid=root;pwd=root;database=hangfire;Allow User Variables=True";
            var storage          = new MySqlStorage(connectionString, options);

            GlobalConfiguration.Configuration.UseStorage(storage);
            SetJobSchedule();

            using (var server = new BackgroundJobServer())
            {
                Console.WriteLine("Hangfire Server started. Press any key to exit...");

                Console.ReadKey();
            }
        }
        public void Set_QueuePollInterval_ShouldThrowAnException_WhenGivenIntervalIsNegative()
        {
            var options = new MySqlStorageOptions();

            Assert.Throws <ArgumentException>(
                () => options.QueuePollInterval = TimeSpan.FromSeconds(-1));
        }
Exemple #5
0
        public static void ConfigurationHangfire(this IServiceCollection services, IConfiguration Configuration,
                                                 IGlobalConfiguration globalConfiguration)
        {
            var serverProvider   = services.BuildServiceProvider();
            var hangfireSettings = serverProvider.GetService <IOptions <HangfireSettings> >().Value;
            var httpJobOptions   = serverProvider.GetService <IOptions <HangfireHttpJobOptions> >().Value;

            var sqlConnectStr = Configuration.GetSection(HangfireConnectStringKey).Get <string>();

            var mysqlOption = new MySqlStorageOptions
            {
                TransactionIsolationLevel  = IsolationLevel.ReadCommitted,
                QueuePollInterval          = TimeSpan.FromSeconds(15),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval  = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary   = true,
                DashboardJobListLimit      = 50000,
                TransactionTimeout         = TimeSpan.FromMinutes(1),
                TablesPrefix = hangfireSettings.TablePrefix
            };

            globalConfiguration.UseStorage(new MySqlStorage(sqlConnectStr, mysqlOption))
            .UseConsole(new ConsoleOptions
            {
                BackgroundColor = "#000079"
            })
            .UseHangfireHttpJob(httpJobOptions)
            .UseTagsWithMySql(new TagsOptions()
            {
                TagsListStyle = TagsListStyle.Dropdown
            }, sqlOptions: mysqlOption)
            .UseHeartbeatPage();
        }
        public void Set_QueuePollInterval_SetsTheValue()
        {
            var options = new MySqlStorageOptions();

            options.QueuePollInterval = TimeSpan.FromSeconds(1);
            Assert.Equal(TimeSpan.FromSeconds(1), options.QueuePollInterval);
        }
        public void Set_QueuePollInterval_ShouldThrowAnException_WhenGivenIntervalIsEqualToZero()
        {
            var options = new MySqlStorageOptions();

            Assert.Throws <ArgumentException>(
                () => options.QueuePollInterval = TimeSpan.Zero);
        }
Exemple #8
0
        public MySqlFetchedJob(
            ElasticStorage.ElasticStorage storage,
            IDbConnection connection,
            FetchedJob fetchedJob,
            MySqlStorageOptions storageOptions)
        {
            if (storage == null)
            {
                throw new ArgumentNullException("storage");
            }
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }
            if (fetchedJob == null)
            {
                throw new ArgumentNullException("fetchedJob");
            }

            _storage        = storage;
            _connection     = connection;
            _storageOptions = storageOptions;
            _id             = fetchedJob.Id;
            JobId           = fetchedJob.JobId.ToString(CultureInfo.InvariantCulture);
            Queue           = fetchedJob.Queue;
        }
        public static IServiceCollection ConfigureScheduleHangFire(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddHostedService <TimerHostedService>();

            // MYSQL
            {
                var options = new MySqlStorageOptions
                {
                    TransactionIsolationLevel  = IsolationLevel.ReadCommitted,
                    QueuePollInterval          = TimeSpan.FromSeconds(15),
                    JobExpirationCheckInterval = TimeSpan.FromHours(1),
                    CountersAggregateInterval  = TimeSpan.FromMinutes(5),
                    PrepareSchemaIfNecessary   = true,
                    DashboardJobListLimit      = 50000,
                    TransactionTimeout         = TimeSpan.FromMinutes(1),
                    TablesPrefix = "Hangfire"
                };

                var connectionString = configuration.GetConnectionString("HangFireMysql");
                var storage          = new MySqlStorage(connectionString, options);
                GlobalConfiguration.Configuration.UseStorage(storage);
            }

            // SQL SERVER
            // {
            //     var connectionString = this.Configuration.GetConnectionString("HangFireSqlServer");
            //     services.AddHangfire(x => x.UseSqlServerStorage(connectionString));
            // }

            return(services);
        }
        public MySqlJobQueue(MySqlStorage storage, MySqlStorageOptions options)
        {
            if (storage == null) throw new ArgumentNullException("storage");
            if (options == null) throw new ArgumentNullException("options");

            _storage = storage;
            _options = options;
        }
        public MySqlJobQueueProvider(MySqlStorage storage, MySqlStorageOptions options)
        {
            if (storage == null) throw new ArgumentNullException("storage");
            if (options == null) throw new ArgumentNullException("options");

            _jobQueue = new MySqlJobQueue(storage, options);
            _monitoringApi = new MySqlJobQueueMonitoringApi(storage);
        }
        public void Ctor_SetsTheDefaultOptions()
        {
            var options = new MySqlStorageOptions();

            Assert.True(options.QueuePollInterval > TimeSpan.Zero);
            Assert.True(options.InvisibilityTimeout > TimeSpan.Zero);
            Assert.True(options.JobExpirationCheckInterval > TimeSpan.Zero);
            Assert.True(options.PrepareSchemaIfNecessary);
        }
        public void Ctor_SetsTheDefaultOptions()
        {
            var options = new MySqlStorageOptions();

            Assert.True(options.QueuePollInterval > TimeSpan.Zero);
            Assert.True(options.InvisibilityTimeout > TimeSpan.Zero);
            Assert.True(options.JobExpirationCheckInterval > TimeSpan.Zero);
            Assert.True(options.PrepareSchemaIfNecessary);
        }
 public MySqlJobQueueMonitoringApi(MySqlStorage storage, MySqlStorageOptions storageOptions)
 {
     if (storage == null)
     {
         throw new ArgumentNullException("storage");
     }
     _storage        = storage;
     _storageOptions = storageOptions;
 }
        private void Configuration(IGlobalConfiguration globalConfiguration)
        {
            var mysqlOption = new MySqlStorageOptions
            {
                TransactionIsolationLevel  = IsolationLevel.ReadCommitted,
                QueuePollInterval          = TimeSpan.FromSeconds(15),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval  = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary   = true,
                DashboardJobListLimit      = 50000,
                TransactionTimeout         = TimeSpan.FromMinutes(1),
                TablesPrefix = "hangfire"
            };

            globalConfiguration.UseStorage(
                new MySqlStorage(
                    JsonConfig.GetSection("HangfireMysqlConnectionString").Get <string>()
                    , mysqlOption
                    ))
            .UseConsole(new ConsoleOptions()
            {
                BackgroundColor = "#000079"
            })
            .UseHangfireHttpJob(new HangfireHttpJobOptions
            {
                MailOption = new MailOption
                {
                    Server   = JsonConfig.GetSection("HangfireMail:Server").Get <string>(),
                    Port     = JsonConfig.GetSection("HangfireMail:Port").Get <int>(),
                    UseSsl   = JsonConfig.GetSection("HangfireMail:UseSsl").Get <bool>(),
                    User     = JsonConfig.GetSection("HangfireMail:User").Get <string>(),
                    Password = JsonConfig.GetSection("HangfireMail:Password").Get <string>(),
                },
                DefaultRecurringQueueName     = JsonConfig.GetSection("DefaultRecurringQueueName").Get <string>(),
                DefaultBackGroundJobQueueName = "DEFAULT",
                DefaultTimeZone = "Asia/Shanghai",
                //EnableDingTalk = true,
                //CurrentDomain = "http://localhost:5000"
                //RecurringJobTimeZone = TimeZoneInfo.Local,
                // CheckHttpResponseStatusCode = code => (int)code < 400   //===》(default)
                //AddHttpJobFilter = (jobContent) =>
                //{
                //    //添加httpjob的拦截器 如果返回false就代表不添加 返回true则真正的添加

                //    if (jobContent.Url.StartsWith("http://localhost") ||
                //        jobContent.Url.StartsWith("http://127.0.0.1"))
                //    {
                //        return true;
                //    }

                //    return false;
                //}
            })
            .UseTagsWithMySql(sqlOptions: mysqlOption)
            .UseHeartbeatPage();
        }
Exemple #16
0
        private ExpirationManager CreateManager(MySqlConnection connection)
        {
            var options = new MySqlStorageOptions
            {
                JobExpirationCheckInterval = TimeSpan.Zero
            };
            var storage = new MySqlStorage(connection, options);

            return(new ExpirationManager(storage, options));
        }
        public MySqlMonitoringApi([NotNull] ElasticStorage.ElasticStorage storage, MySqlStorageOptions storageOptions)
        {
            if (storage == null)
            {
                throw new ArgumentNullException("storage");
            }

            _storage        = storage;
            _storageOptions = storageOptions;
        }
        public MySqlJobQueueMonitoringApiTests()
        {
            _connection = new MySqlConnection(ConnectionUtils.GetConnectionString());
            _connection.Open();

            var storageOptions = new MySqlStorageOptions();

            _storage = new ElasticStorage.ElasticStorage(_connection, storageOptions);
            _sut     = new MySqlJobQueueMonitoringApi(_storage, storageOptions);
        }
        public static IServiceCollection AddHangfireServices(this IServiceCollection services, IConfiguration config)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            services.Configure <BackgroundJobSettings>(config.GetSection(ConfigurationKeys.BackgroundJobs));

            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute {
                Attempts = 10
            });

            var mySqlOptions = new MySqlStorageOptions
            {
                QueuePollInterval          = TimeSpan.FromSeconds(15),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval  = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary   = true,
                DashboardJobListLimit      = 50000,
                TransactionTimeout         = TimeSpan.FromMinutes(1),
                TablesPrefix = "Hangfire"
            };

            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseHeartbeatPage(TimeSpan.FromSeconds(1.5))
                                 .UseJobsLogger(new JobsLoggerOptions
            {
                LogLevel            = LogLevelFromString(config[ConfigurationKeys.HangfireJobsLoggerLevel]),
                LogCriticalColor    = Color.DarkRed,
                LogErrorColor       = Color.Red,
                LogWarningColor     = Color.DarkOrange,
                LogInformationColor = Color.DarkGreen,
                LogDebugColor       = Color.Gray
            })
                                 .UseColouredConsoleLogProvider(LogLevel.Warn)
                                 // Can't use tags yet. Issue with Pomelo ef core MySQL connector. Also won't work with using Hangfire.Storage.MySql;
                                 // .UseTagsWithMySql(new TagsOptions { TagsListStyle = TagsListStyle.Dropdown }, mySqlOptions)
                                 .UseStorage(new MySqlStorage(GetHangfireMySqlConnectionString(config[ConfigurationKeys.HangfireDatabaseName], config[ConfigurationKeys.HangfireDatabaseConnection]), mySqlOptions))
                                 );

            services.AddTransient <PullAuctionDataBackgroundJob>();

            services.AddHangfireServer();

            return(services);
        }
Exemple #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connString = Configuration["ConnectionString"];

            services.AddDbContext <AppDBContext>(opts => opts.UseMySQL(connString));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //var storage = JobStorage.Current;

            //GlobalConfiguration.Configuration.UseStorage(new MySqlStorage(connString));

            //storage = JobStorage.Current;
            services.AddHangfire(config =>
            {
                var options = new MySqlStorageOptions
                {
                    QueuePollInterval = TimeSpan.FromMinutes(5)
                };
                config.UseStorage(new MySqlStorage(connString, options));
            });


            services.AddScoped <IDataRepository <PaymentOption>, PaymentOptionDataRepository>();
            services.AddScoped <IPaymentOptions, PaymentOptionsService>();
            services.AddScoped <IDataRepository <Bank>, BanksRepository>();
            services.AddScoped <IBankService, BankService>();

            services.AddScoped <IDataRepository <Transaction>, TransactionRespository>();
            services.AddScoped <ITransactionService, TransactionService>();


            services.AddSingleton <IReportJob, ReportJob>();


            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "My API",
                    Description    = "Payment GateWay Web API",
                    TermsOfService = "None",
                    Contact        = new Contact()
                    {
                        Name = "Paymentgateway", Email = "*****@*****.**", Url = "www.google.com"
                    }
                });
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
Exemple #21
0
        public MySqlMonitoringApi([NotNull] MySqlStorage storage, MySqlStorageOptions options, int?jobListLimit)
        {
            if (storage == null)
            {
                throw new ArgumentNullException("storage");
            }

            _storage      = storage;
            _options      = options;
            _jobListLimit = jobListLimit;
        }
Exemple #22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddHangfire(conf =>
            {
                var mySqlStorageOptions = new MySqlStorageOptions()
                {
                    TransactionIsolationLevel  = IsolationLevel.ReadCommitted, // 事务隔离级别。默认是读取已提交。
                    QueuePollInterval          = TimeSpan.FromSeconds(1),      //TimeSpan.FromSeconds(15), // 作业队列轮询间隔。默认值为15秒。
                    JobExpirationCheckInterval = TimeSpan.FromHours(1),        // 作业到期检查间隔(管理过期记录)。默认值为1小时。
                    CountersAggregateInterval  = TimeSpan.FromMinutes(5),      // 聚合计数器的间隔。默认为5分钟。
                    PrepareSchemaIfNecessary   = true,                         // 如果设置为true,则创建数据库表。默认是true。
                    DashboardJobListLimit      = 50000,                        // 仪表板作业列表限制。默认值为50000。
                    TransactionTimeout         = TimeSpan.FromMinutes(1),      //事务超时。默认为1分钟。
                    TablePrefix = "Hangfire"                                   //数据库表前缀
                };

                // 持久化数据库
                conf.UseStorage <MySqlStorage>(new MySqlStorage(
                                                   Configuration.GetSection("Hangfire:ConnectionString").Get <string>()
                                                   , mySqlStorageOptions))
                // 设置控制台显示
                .UseConsole(new ConsoleOptions()
                {
                    BackgroundColor = "#000079"
                })
                // HttpJob
                .UseHangfireHttpJob(new HangfireHttpJobOptions()
                {
                    // 设置面板的标题与页脚
                    DashboardName   = Configuration.GetSection("Hangfire:DashboardName").Get <string>(),
                    DashboardFooter = Configuration.GetSection("Hangfire:DashboardFooter").Get <string>(),
                    // 错误发送邮箱
                    MailOption = new MailOption()
                    {
                        Server   = Configuration.GetSection("Hangfire:Mail:Server").Get <string>(),
                        Port     = Configuration.GetSection("Hangfire:Mail:Port").Get <int>(),
                        User     = Configuration.GetSection("Hangfire:Mail:User").Get <string>(),
                        Password = Configuration.GetSection("Hangfire:Mail:Password").Get <string>(),
                        UseSsl   = Configuration.GetSection("Hangfire:Mail:UseSsl").Get <bool>()
                    },
                    // 默认周期性作业的队列名称
                    DefaultRecurringQueueName = Configuration.GetSection("Hangfire:DefaultRecurringQueueName").Get <string>()
                })
                .UseTagsWithMysql(sqlOptions: mySqlStorageOptions);
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Exemple #23
0
        public CountersAggregatorTests()
        {
            var options = new MySqlStorageOptions
            {
                CountersAggregateInterval = TimeSpan.Zero
            };

            _connection = ConnectionUtils.CreateConnection();
            _storage    = new MySqlStorage(_connection, options);
            _sut        = new CountersAggregator(_storage, options);
        }
 public MySqlFetchedJobTests()
 {
     _fetchedJob = new FetchedJob()
     {
         Id = _id, JobId = JobId, Queue = Queue
     };
     _connection     = new Mock <IDbConnection>();
     _storageOptions = new MySqlStorageOptions {
         PrepareSchemaIfNecessary = false
     };
     _storage = new Mock <ElasticStorage.ElasticStorage>(ConnectionUtils.GetConnectionString(), _storageOptions);
 }
Exemple #25
0
        public void CreateDefaultStorage()
        {
            SpiderOptions options = new SqlServerStorageOptions();

            ;
            // SqlServer
            var storage1 = (SqlServerEntityStorage)Spider.GetDefaultStorage(options);

            Assert.Equal("ConnectionString", storage1.ConnectionString);
            Assert.Equal(800, storage1.RetryTimes);
            Assert.True(storage1.UseTransaction);
            Assert.False(storage1.IgnoreCase);
            Assert.Equal(StorageType.InsertAndUpdate, storage1.StorageType);

            // MySql
            options = new MySqlStorageOptions();

            var storage2 = (MySqlEntityStorage)Spider.GetDefaultStorage(options);

            Assert.Equal("ConnectionString", storage2.ConnectionString);
            Assert.Equal(800, storage2.RetryTimes);
            Assert.True(storage2.UseTransaction);
            Assert.False(storage2.IgnoreCase);
            Assert.Equal(StorageType.InsertAndUpdate, storage2.StorageType);

            // MySqlFile
            options = new MySqlFileStorageOptions();

            var storage3 = (MySqlFileEntityStorage)Spider.GetDefaultStorage(options);

            Assert.False(storage3.IgnoreCase);
            Assert.Equal(MySqlFileType.LoadFile, storage3.MySqlFileType);

            // PostgreSql
            options = new PostgreSqlStorageOptions();

            var storage4 = (PostgreSqlEntityStorage)Spider.GetDefaultStorage(options);

            Assert.Equal("ConnectionString", storage4.ConnectionString);
            Assert.Equal(800, storage4.RetryTimes);
            Assert.True(storage4.UseTransaction);
            Assert.False(storage4.IgnoreCase);
            Assert.Equal(StorageType.InsertAndUpdate, storage4.StorageType);

            // Mongo
            options = new MongoStorageOptions();
            ;

            var storage5 = (MongoEntityStorage)Spider.GetDefaultStorage(options);

            Assert.Equal("mongodb://mongodb0.example.com:27017/admin", storage5.ConnectionString);
        }
Exemple #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o =>
            {
                o.ExpireTimeSpan = TimeSpan.FromMinutes(480);    //cookie默认有效时间为8个小时
                o.LoginPath      = new PathString("/Home/Login");
                o.LogoutPath     = new PathString("/Home/Logout");
                o.Cookie         = new CookieBuilder
                {
                    HttpOnly = true,
                    Name     = ".JuCheap.Core.Identity",
                    Path     = "/"
                };
                //o.DataProtectionProvider = null;//如果需要做负载均衡,就需要提供一个Key
            });
            //使用Sql Server数据库
            //services.AddDbContext<JuCheapContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Connection_SqlServer")));

            ////使用Sqlite数据库
            //services.AddDbContext<JuCheapContext>(options => options.UseSqlite(Configuration.GetConnectionString("Connection_Sqlite")));

            //使用MySql数据库
            services.AddDbContext <JuCheapContext>(options => options.UseMySql(Configuration.GetConnectionString("Connection_MySql")));

            //权限验证filter
            services.AddMvc(cfg =>
            {
                cfg.Filters.Add(new RightFilter());
            });
            //.AddJsonOptions(option => option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());//配置大小写问题,默认是首字母小写

            // service依赖注入
            services.UseJuCheapService();

            //hangfire自动任务配置数据库配置
            //使用sql server数据库做hangfire的持久化
            //services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("Connection_Job_SqlServer")));

            //使用mysql数据库做hangfire的持久化
            //使用mysql的时候,由于很同学不知道怎么设置数据库和数据表的编码格式,会导致hangfire初始化失败,
            //所以不自动创建hangfire的数据表,需要手动导入根目录下Hangfire/hangfire.job.mysql.sql文件来创建表
            var mySqlOption = new MySqlStorageOptions
            {
                PrepareSchemaIfNecessary = false
            };

            services.AddHangfire(x => x.UseStorage(new MySqlStorage(Configuration.GetConnectionString("Connection_Job_MySql"), mySqlOption)));
        }
        public MySqlJobQueueProvider(MySqlStorage storage, MySqlStorageOptions options)
        {
            if (storage == null)
            {
                throw new ArgumentNullException("storage");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _jobQueue      = new MySqlJobQueue(storage, options);
            _monitoringApi = new MySqlJobQueueMonitoringApi(storage, options);
        }
Exemple #28
0
        public MySqlJobQueue(MySqlStorage storage, MySqlStorageOptions options)
        {
            if (storage == null)
            {
                throw new ArgumentNullException("storage");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _storage = storage;
            _options = options;
        }
Exemple #29
0
    public static MySqlStorage GetMysqlStorage(string connectionStr)
    {
        var options = new MySqlStorageOptions
        {
            // TransactionIsolationLevel = IsolationLevel.ReadCommitted,
            QueuePollInterval          = TimeSpan.FromSeconds(15),
            JobExpirationCheckInterval = TimeSpan.FromHours(1),
            CountersAggregateInterval  = TimeSpan.FromMinutes(5),
            PrepareSchemaIfNecessary   = true,
            DashboardJobListLimit      = 50000,
            TransactionTimeout         = TimeSpan.FromMinutes(1),
            TablesPrefix = "_hangfire"
        };
        var storage = new MySqlStorage(connectionStr, options);

        return(storage);
    }
        public static void ConfigurationHangfire(this IServiceCollection services, IConfiguration Configuration,
                                                 IGlobalConfiguration globalConfiguration)
        {
            var serverProvider   = services.BuildServiceProvider();
            var hangfireSettings = serverProvider.GetService <IOptions <HangfireSettings> >().Value;

            ConfigFromEnv(hangfireSettings);
            var httpJobOptions = serverProvider.GetService <IOptions <HangfireHttpJobOptions> >().Value;

            ConfigFromEnv(httpJobOptions);

            httpJobOptions.GlobalSettingJsonFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "hangfire",
                                                                    "hangfire_global.json");

            var sqlConnectStr    = Configuration.GetSection(HangfireConnectStringKey).Get <string>();
            var envSqlConnectStr = GetEnvConfig <string>("HangfireMysqlConnectionString");

            if (!string.IsNullOrEmpty(envSqlConnectStr))
            {
                sqlConnectStr = envSqlConnectStr;
            }

            var mysqlOption = new MySqlStorageOptions
            {
                TransactionIsolationLevel  = IsolationLevel.ReadCommitted,
                QueuePollInterval          = TimeSpan.FromSeconds(15),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval  = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary   = true,
                DashboardJobListLimit      = 50000,
                TransactionTimeout         = TimeSpan.FromMinutes(1),
                TablesPrefix = hangfireSettings.TablePrefix
            };

            globalConfiguration.UseStorage(new MySqlStorage(sqlConnectStr, mysqlOption))
            .UseConsole(new ConsoleOptions
            {
                BackgroundColor = "#000079"
            })
            .UseHangfireHttpJob(httpJobOptions)
            .UseTagsWithMySql(new TagsOptions()
            {
                TagsListStyle = TagsListStyle.Dropdown
            }, sqlOptions: mysqlOption)
            .UseHeartbeatPage();
        }
Exemple #31
0
        public MysqlTagsTransaction(MySqlStorageOptions options, IWriteOnlyTransaction transaction)
        {
            if (transaction.GetType().Name != "MySqlWriteOnlyTransaction")
            {
                throw new ArgumentException("The transaction is not an SQL transaction", nameof(transaction));
            }

            _options     = options;
            _transaction = transaction;

            // Dirty, but lazy...we would like to execute these commands in the same transaction, so we're resorting to reflection for now

            // Other transaction type, clear cached methods
            if (_type != transaction.GetType())
            {
                _acquireSetLock = null;
                _queueCommand   = null;

                _type = transaction.GetType();
            }

            if (_acquireSetLock == null)
            {
                _acquireSetLock = transaction.GetType().GetTypeInfo().GetMethod(nameof(AcquireSetLock),
                                                                                BindingFlags.NonPublic | BindingFlags.Instance);
            }

            if (_acquireSetLock == null)
            {
                throw new ArgumentException("The function AcquireSetLock cannot be found.");
            }

            if (_queueCommand == null)
            {
                _queueCommand = transaction.GetType().GetTypeInfo().GetMethod(nameof(QueueCommand),
                                                                              BindingFlags.NonPublic | BindingFlags.Instance);
            }

            if (_queueCommand == null)
            {
                throw new ArgumentException("The functions QueueCommand  cannot be found.");
            }
        }
Exemple #32
0
        public MySqlFetchedJob(
            MySqlStorage storage,
            MySqlStorageOptions options,
            IDbConnection connection,
            FetchedJob fetchedJob)
        {
            _storage    = storage ?? throw new ArgumentNullException(nameof(storage));
            _connection = connection ?? throw new ArgumentNullException(nameof(connection));
            _options    = options ?? throw new ArgumentNullException(nameof(options));

            if (fetchedJob == null)
            {
                throw new ArgumentNullException(nameof(fetchedJob));
            }

            _id   = fetchedJob.Id;
            JobId = fetchedJob.JobId.ToString(CultureInfo.InvariantCulture);
            Queue = fetchedJob.Queue;
        }
Exemple #33
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSingleton <DapperHelper>();

            services.AddScoped <FundCodeService>();
            services.AddScoped <FundDataDayService>();
            services.AddScoped <FundDataMinService>();

            var storageOptions = new MySqlStorageOptions();

            storageOptions.TablePrefix = "Job";
            services.AddHangfire(x => x.UseStorage(new MySqlStorage(DapperHelper.ConnectionString, storageOptions)));
            services.AddHangfireServer();

            HangfireTask.Instance.Services = services;

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(x =>
            {
                x.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                x.SerializerSettings.Formatting       = Newtonsoft.Json.Formatting.None;
            });

            services.AddCors(options => options.AddPolicy("CorsBoard",
                                                          p => p.WithOrigins("http://localhost:55161"
                                                                             , "http://localhost:8081"
                                                                             , "http://localhost:8080"
                                                                             , "http://localhost:5000"
                                                                             )
                                                          .AllowAnyMethod()
                                                          .AllowAnyHeader()
                                                          )
                             );
        }
 public void Set_QueuePollInterval_SetsTheValue()
 {
     var options = new MySqlStorageOptions();
     options.QueuePollInterval = TimeSpan.FromSeconds(1);
     Assert.Equal(TimeSpan.FromSeconds(1), options.QueuePollInterval);
 }
 public void Set_QueuePollInterval_ShouldThrowAnException_WhenGivenIntervalIsEqualToZero()
 {
     var options = new MySqlStorageOptions();
     Assert.Throws<ArgumentException>(
         () => options.QueuePollInterval = TimeSpan.Zero);
 }
 public void Set_QueuePollInterval_ShouldThrowAnException_WhenGivenIntervalIsNegative()
 {
     var options = new MySqlStorageOptions();
     Assert.Throws<ArgumentException>(
         () => options.QueuePollInterval = TimeSpan.FromSeconds(-1));
 }