public static void AddHangFile(this IServiceCollection services, IConfiguration configuration)
        {
            //是否启动Hangfire
            var enabled = configuration["AppSettings:HangFire:Enabled"];

            if (!string.IsNullOrWhiteSpace(enabled) && bool.Parse(enabled))
            {
                var conn      = configuration["AppSettings:HangFire:RedisConnectionString"];
                var prefix    = configuration["AppConfig:HangFire:RedisPrefixName"];
                var defaultDb = configuration["AppConfig:HangFire:RedisDefaultDatabase"];
                var option    = new RedisStorageOptions
                {
                    Db     = 0,
                    Prefix = prefix
                };
                if (int.TryParse(defaultDb, out int db))
                {
                    if (db >= 0 && db <= 15)
                    {
                        option.Db = db;
                    }
                }
                services.AddHangfire(config => { config.UseRedisStorage(conn, option); });
            }
        }
        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 options = new RedisStorageOptions
            {
                Prefix            = hangfireSettings.TablePrefix,
                SucceededListSize = 9999,
                DeletedListSize   = 4999,
            };
            var redis = ConnectionMultiplexer.Connect(sqlConnectStr);

            globalConfiguration.UseRedisStorage(redis, options)
            .UseConsole(new ConsoleOptions
            {
                BackgroundColor = "#000079"
            })
            .UseTagsWithRedis(new TagsOptions()
            {
                TagsListStyle = TagsListStyle.Dropdown
            })
            .UseHangfireHttpJob(httpJobOptions)
            .UseHeartbeatPage();
        }
        public FetchedJobsWatcherFacts()
        {
            var options = new RedisStorageOptions() { Db = RedisUtils.GetDb() };
            _storage = new RedisStorage(RedisUtils.GetHostAndPort(), options);
			_cts = new CancellationTokenSource();
			_cts.Cancel();
        }
Exemple #4
0
        public void ShouldUseProvidedRedisOptions()
        {
            var system = new SystemUnderTest();

            system.ConfigurationStorage.Has(new StoredConfiguration {
                ConnectionString = "redis"
            });
            var options = new RedisStorageOptions
            {
                MultiplexerPoolSize        = 1,
                Database                   = 42,
                InvisibilityTimeout        = TimeSpan.FromMinutes(11),
                MaxSucceededListLength     = 22,
                MaxDeletedListLength       = 33,
                MaxStateHistoryLength      = 44,
                CheckCertificateRevocation = false
            };

            system.UseStorageOptions(options);

            system.WorkerServerStarter.Start();

            var actual = system.Hangfire.StartedServers.Single().storage.RedisOptions();

            actual.Should().Not.Be.SameInstanceAs(options);
            actual.MultiplexerPoolSize.Should().Be.EqualTo(1);
            actual.Database.Should().Be.EqualTo(42);
            actual.InvisibilityTimeout.Should().Be.EqualTo(TimeSpan.FromMinutes(11));
            actual.MaxSucceededListLength.Should().Be.EqualTo(22);
            actual.MaxDeletedListLength.Should().Be.EqualTo(33);
            actual.MaxStateHistoryLength.Should().Be.EqualTo(44);
            actual.CheckCertificateRevocation.Should().Be.EqualTo(false);
        }
        public void Initialize(IAppBuilder appBuilder)
        {
            var redisStorageOptions = new RedisStorageOptions()
            {
                Db     = _configWrapper.HangfireRedisDb,
                Prefix = _configWrapper.HangfireRedisPrefix
            };

            Console.WriteLine(_configWrapper.RedisConnectionString);

            _jobStorage = new RedisStorage(_configWrapper.RedisConnectionString, redisStorageOptions);

            GlobalConfiguration.Configuration.UseStorage(_jobStorage);

            JobActivator.Current = new WindsorJobActivator(ServiceContext.Instance.WindsorContainer.Kernel);

            appBuilder.UseHangfireDashboard(_configWrapper.HangfireDashboardUrl, new DashboardOptions()
            {
                Authorization = new[] { new CustomDashboardAuthorizationFilter() },
            });

            appBuilder.UseHangfireServer(new BackgroundJobServerOptions()
            {
                WorkerCount = _configWrapper.HangfireWorkerCount,
                Queues      = _configWrapper.HangfireQueues,
                Activator   = JobActivator.Current
            });
        }
        public RedisTagsMonitoringApi(IMonitoringApi monitoringApi, RedisStorageOptions options)
        {
            if (monitoringApi.GetType().Name != "RedisMonitoringApi")
            {
                throw new ArgumentException("The monitor API is not implemented using Redis", nameof(monitoringApi));
            }
            _monitoringApi = monitoringApi;

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

            var databaseFactory = monitoringApi.GetType().GetTypeInfo().GetField("_databaseFactory",
                                                                                 BindingFlags.NonPublic | BindingFlags.Instance);

            if (databaseFactory == null)
            {
                throw new ArgumentException("The field _databaseFactory cannot be found.");
            }

            var getJobsWithPropertiesMethod = monitoringApi.GetType()
                                              .GetMethod("GetJobsWithProperties", BindingFlags.Instance | BindingFlags.NonPublic);

            if (getJobsWithPropertiesMethod == null)
            {
                throw new ArgumentException("The method GetJobsWithPropertiesMethod cannot be found.");
            }

            _getJobsWithPropertiesMethod = getJobsWithPropertiesMethod.MakeGenericMethod(typeof(MatchingJobDto));

            var factory    = (Func <object>)databaseFactory.GetValue(monitoringApi);
            var objFactory = factory.Invoke();

            _wrapper = new DatabaseWrapper(objFactory, options);
        }
        public RedisWriteOnlyTransactionFacts()
        {
            var options = new RedisStorageOptions()
            {
            };

            _storage = new RedisStorage(RedisUtils.RedisClient, options);
        }
Exemple #8
0
 public DbConnection(
     RedisStorageOptions options,
     ILogger <DbConnection> logger
     )
 {
     _logger  = logger;
     _options = options;
 }
        //[Fact]
        //public void DbFromConnectionStringIsUsed()
        //{
        //    var storage = new RedisStorage(String.Format("{0},defaultDatabase=5", RedisUtils.GetHostAndPort()));
        //    Assert.Equal(5, storage.Db);
        //}

        private RedisStorage CreateStorage()
        {
            var options = new RedisStorageOptions()
            {
            };

            return(new RedisStorage(RedisUtils.RedisClient, options));
        }
Exemple #10
0
        public RedisFetchedJobFacts()
        {
            var options = new RedisStorageOptions()
            {
            };

            _storage = new RedisStorage(RedisUtils.RedisClient, options);
        }
Exemple #11
0
 public StateHandler(RedisStorageOptions options, IConnectionMultiplexer multiplexer)
 {
     SucceededListSize = options.SucceededListSize > 0 ? options.SucceededListSize : 1000;
     DeletedListSize   = options.DeletedListSize > 0 ? options.DeletedListSize : 1000;
     _useTransactions  = options.UseTransactions;
     _database         = multiplexer.GetDatabase();
     _prefix           = options.Prefix;
 }
        public RedisConnectionFacts()
        {
            var options = new RedisStorageOptions()
            {
            };

            _storage = new RedisStorage(RedisUtils.RedisClient, options);
        }
Exemple #13
0
        public static void ConfigurationHangfire(this IServiceCollection services, IConfiguration configuration,
                                                 IGlobalConfiguration globalConfiguration)
        {
            var serverProvider = services.BuildServiceProvider();

            var langStr    = configuration.GetSection(HangfireLangKey).Get <string>();
            var envLangStr = GetEnvConfig <string>("Lang");

            if (!string.IsNullOrEmpty(envLangStr))
            {
                langStr = envLangStr;
            }
            if (!string.IsNullOrEmpty(langStr))
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(langStr);
            }

            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>("HangfireRedisConnectionString");

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

            var options = new RedisStorageOptions
            {
                Prefix            = hangfireSettings.TablePrefix,
                SucceededListSize = 9999,
                DeletedListSize   = 4999,
                UseTransactions   = false
            };
            var redis = ConnectionMultiplexer.Connect(sqlConnectStr);

            globalConfiguration.UseRedisStorage(redis, options)
            .UseConsole(new ConsoleOptions
            {
                BackgroundColor = "#000079"
            })
            .UseTagsWithRedis(new TagsOptions()
            {
                TagsListStyle = TagsListStyle.Dropdown
            }, options)
            .UseHangfireHttpJob(httpJobOptions)
            .UseHeartbeatPage();
        }
        public RedisConnectionFacts()
        {
            var options = new RedisStorageOptions()
            {
                Db = RedisUtils.GetDb()
            };

            _storage = new RedisStorage(RedisUtils.GetHostAndPort(), options);
        }
        private RedisStorage CreateStorage()
        {
            var options = new RedisStorageOptions()
            {
                Db = RedisUtils.GetDb()
            };

            return(new RedisStorage(RedisUtils.GetHostAndPort(), options));
        }
        public RedisSubscriptionFacts()
        {
            _cts = new CancellationTokenSource();

            var options = new RedisStorageOptions()
            {
            };

            _storage = new RedisStorage(RedisUtils.RedisClient, options);
        }
        public RedisTagsTransaction(RedisStorageOptions options, IWriteOnlyTransaction transaction, IDatabase database)
        {
            if (options.UseTransactions && transaction.GetType().Name != "RedisWriteOnlyTransaction")
            {
                throw new ArgumentException("The transaction is not an Redis transaction", nameof(transaction));
            }

            _database = database;
            _options  = options;
        }
        public ExpiredJobsWatcherFacts()
        {
            var options = new RedisStorageOptions()
            {
            };

            _storage = new RedisStorage(RedisUtils.RedisClient, options);
            _cts     = new CancellationTokenSource();
            _cts.Cancel();
        }
Exemple #19
0
        public static void ConfigureHangfire(this IServiceCollection services, string connectionString, Action <RedisStorageOptions> configureRedis = null, Action <IGlobalConfiguration> configureHangfire = null)
        {
            services.AddHangfire(globalConfiguration =>
            {
                var redisStorageOptions = new RedisStorageOptions();

                configureRedis?.Invoke(redisStorageOptions);
                configureHangfire?.Invoke(globalConfiguration);
                globalConfiguration.UseRedisStorage(connectionString, redisStorageOptions);
            });
        }
Exemple #20
0
        public RedisWriteOnlyTransactionFacts()
        {
            var options = new RedisStorageOptions()
            {
                Db = RedisUtils.GetDb()
            };

            _storage = new RedisStorage(RedisUtils.GetHostAndPort(), options);

            _transaction = new Mock <ITransaction>();
        }
        /// <summary>
        /// Tells the bootstrapper to use Redis as a job storage with
        /// the given options, available at the specified host and port,
        /// and store the data in the given database number. 
        /// </summary>
        /// <param name="configuration">Configuration</param>
        /// <param name="hostAndPort">Host and port, for example 'localhost:6379'</param>
        /// <param name="db">Database number to store the data, for example '0'</param>
        /// <param name="options">Advanced storage options</param>
        public static RedisStorage UseRedisStorage(
            this IBootstrapperConfiguration configuration,
            string hostAndPort,
            int db,
            RedisStorageOptions options)
        {
            var storage = new RedisStorage(hostAndPort, db, options);
            configuration.UseStorage(storage);

            return storage;
        }
Exemple #22
0
        public RedisFetchedJobFacts()
        {
            _redis = new Mock <IDatabase>();

            var options = new RedisStorageOptions()
            {
                Db = RedisUtils.GetDb()
            };

            _storage = new RedisStorage(RedisUtils.GetHostAndPort(), options);
        }
Exemple #23
0
        public FetchedJobsWatcherFacts()
        {
            var options = new RedisStorageOptions()
            {
                Db = RedisUtils.GetDb()
            };

            _storage = new RedisStorage(RedisUtils.GetHostAndPort(), options);
            _cts     = new CancellationTokenSource();
            _cts.Cancel();
        }
Exemple #24
0
 public GrainStateStore(
     DbConnection connection,
     RedisStorageOptions options,
     ISerializer serializer,
     IHumanReadableSerializer humanReadableSerializer
     )
 {
     _connection = connection;
     _serializer = serializer;
     _humanReadableSerializer = humanReadableSerializer;
     _options = options;
 }
        /// <summary>
        /// Tells the bootstrapper to use Redis as a job storage with
        /// the given options, available at the specified host and port,
        /// and store the data in the given database number.
        /// </summary>
        /// <param name="configuration">Configuration</param>
        /// <param name="hostAndPort">Host and port, for example 'localhost:6379'</param>
        /// <param name="db">Database number to store the data, for example '0'</param>
        /// <param name="options">Advanced storage options</param>
        public static RedisStorage UseRedisStorage(
            this IBootstrapperConfiguration configuration,
            string hostAndPort,
            int db,
            RedisStorageOptions options)
        {
            var storage = new RedisStorage(hostAndPort, db, options);

            configuration.UseStorage(storage);

            return(storage);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region 日志NLOG

            /*var nLogConfig = new ConfigurationBuilder()
             *  .SetBasePath(System.IO.Directory.GetCurrentDirectory())
             *  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
             *  .Build();
             * LogManager.Configuration = new NLogLoggingConfiguration(nLogConfig.GetSection("NLog"));*/
            NLog.LogManager.LoadConfiguration("NLog.Config");
            //loggerFactory.AddNLog();
            services.AddLogging(loggingBuilder =>
            {
                // configure Logging with NLog
                loggingBuilder.ClearProviders();
                loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                //loggingBuilder.AddNLog(nLogConfig);
                loggingBuilder.AddNLog();
            });

            #endregion


            #region Hangfire配置
            // Add Hangfire services.
            var redisStorageOptions = new RedisStorageOptions();
            redisStorageOptions.Db = 0;
            //任务过期检查频率
            redisStorageOptions.ExpiryCheckInterval = TimeSpan.FromHours(1);
            //redisStorageOptions.Prefix = null;
            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseRedisStorage(Configuration["HangfireConnection"], redisStorageOptions)
                                 .UseConsole()
                                 );

            // Add the processing server as IHostedService
            //Configure方法中与则该方法可以不调用
            services.AddHangfireServer(opt =>
            {
                opt.WorkerCount = 1;
                //队列名要小写
                opt.Queues     = new[] { "news", "default" };
                opt.ServerName = Environment.MachineName + "Web1";
            });

            #endregion

            services.AddControllersWithViews();
        }
        public RedisSubscriptionFacts()
        {
            _cts = new CancellationTokenSource();

            var options = new RedisStorageOptions()
            {
                Db = RedisUtils.GetDb()
            };

            _storage = new RedisStorage(RedisUtils.GetHostAndPort(), options);

            _subscriber = new Mock <ISubscriber>();
        }
        private static RedisStorageOptions ConfigureHangfireRedisStorageOptions(
            global::Apexnet.JobQueue.Configuration.RedisStorageOptions configuration)
        {
            var options = new RedisStorageOptions();

            configuration.Db.InvokeConditionally(value => options.Db = value);
            configuration.InvisibilityTimeout.InvokeConditionally(value => options.InvisibilityTimeout = value);
            configuration.Prefix.InvokeConditionally(
                s => !string.IsNullOrWhiteSpace(s),
                value => options.Prefix = value);

            return options;
        }
Exemple #29
0
        private static RedisStorageOptions ConfigureHangfireRedisStorageOptions(
            global::Apexnet.JobQueue.Configuration.RedisStorageOptions configuration)
        {
            var options = new RedisStorageOptions();

            configuration.Db.InvokeConditionally(value => options.Db = value);
            configuration.InvisibilityTimeout.InvokeConditionally(value => options.InvisibilityTimeout = value);
            configuration.Prefix.InvokeConditionally(
                s => !string.IsNullOrWhiteSpace(s),
                value => options.Prefix = value);

            return(options);
        }
        private void Configuration(IGlobalConfiguration globalConfiguration)
        {
            var redis = ConnectionMultiplexer.Connect(JsonConfig.GetSection("HangfireRedisConnectionString")
                                                      .Get <string>());
            var options = new RedisStorageOptions
            {
                Prefix            = "hangfire:",
                SucceededListSize = 9999,
                DeletedListSize   = 4999,
                Db = redis.GetDatabase().Database
            };

            globalConfiguration.UseRedisStorage(redis, options)
            .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;
                //}
            }).UseTagsWithRedis(redis, redisOptions: options);
        }
        public ExpiredJobsWatcher(RedisStorageOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            _options = options;
            var checkInterval = options.ExpiryCheckInterval;

            if (checkInterval.Ticks <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(checkInterval), "Check interval should be positive.");
            }

            _checkInterval = checkInterval;
        }
Exemple #32
0
        public static IGlobalConfiguration <RedisStorage> UseRedisStorage(
            [NotNull] this IGlobalConfiguration configuration,
            [NotNull] string nameOrConnectionString,
            RedisStorageOptions options = null)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (nameOrConnectionString == null)
            {
                throw new ArgumentNullException(nameof(nameOrConnectionString));
            }
            var storage = new RedisStorage(nameOrConnectionString, options);

            return(configuration.UseStorage(storage));
        }
Exemple #33
0
        public static IGlobalConfiguration <RedisStorage> UseRedisStorage(
            [NotNull] this IGlobalConfiguration configuration,
            [NotNull] ConnectionMultiplexer connectionMultiplexer,
            RedisStorageOptions options = null)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (connectionMultiplexer == null)
            {
                throw new ArgumentNullException("connectionMultiplexer");
            }
            var storage = new RedisStorage(connectionMultiplexer, options);

            return(configuration.UseStorage(storage));
        }
 private RedisStorage CreateStorage()
 {
     var options = new RedisStorageOptions() { Db = RedisUtils.GetDb() };
     return new RedisStorage(RedisUtils.GetHostAndPort(), options);
 }