public CountersAggregator(MySqlStorage storage, TimeSpan interval) { if (storage == null) throw new ArgumentNullException("storage"); _storage = storage; _interval = interval; }
public ExpirationManager(MySqlStorage storage, TimeSpan checkInterval) { if (storage == null) throw new ArgumentNullException("storage"); _storage = storage; _checkInterval = checkInterval; }
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 MySqlJobQueue(MySqlStorage storage, MySqlStorageOptions options) { if (storage == null) throw new ArgumentNullException("storage"); if (options == null) throw new ArgumentNullException("options"); _storage = storage; _options = options; }
public ExpirationManager(MySqlStorage storage, MySqlStorageOptions options, TimeSpan checkInterval) { if (storage == null) { throw new ArgumentNullException("storage"); } _storage = storage; _options = options; _checkInterval = checkInterval; ProcessedTables = new string[] { "AggregatedCounter", "Job", "List", "Set", "Hash" }; }
private static void DoShit1() { var i = 1; var cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler { CookieContainer = cookieContainer }) { using (var client = new HttpClient(handler)) { using (var mySql = new MySqlStorage()) { var nextPage = "https://ru.wiktionary.org/w/index.php?title=%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D1%8F:%D0%90%D0%B1%D0%B1%D1%80%D0%B5%D0%B2%D0%B8%D0%B0%D1%82%D1%83%D1%80%D1%8B/ru&pageuntil=%D0%B1%D0%B8%D0%BE%D1%81%D1%82%D0%B0%D1%82%D0%B8%D1%81%D1%82%D0%B8%D0%BA%D0%B0%0A%D0%B1%D0%B8%D0%BE%D1%81%D1%82%D0%B0%D1%82%D0%B8%D1%81%D1%82%D0%B8%D0%BA%D0%B0#mw-pages"; while (nextPage != null) { var response = client.GetAsync( nextPage) .GetAwaiter() .GetResult(); var html = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); var config = Configuration.Default; var context = BrowsingContext.New(config); var document = context.OpenAsync(req => req.Content(html)).Result; var querySelectorAll = document.QuerySelectorAll(".mw-category-group"); foreach (var div in querySelectorAll) { foreach (var element in div.GetElementsByTagName("a")) { var a = (IHtmlAnchorElement)element; mySql.InsertOrUpdate(new AbbreviationEntity { Id = i++, Title = a.InnerHtml, Link = a.Href.Replace(a.BaseUri, domain) }); } } var nextA = document .GetElementById("mw-pages") .GetElementsByTagName("a") .Select(x => (IHtmlAnchorElement)x) .FirstOrDefault(x => x.InnerHtml == "Следующая страница"); nextPage = nextA?.Href?.Replace(nextA.BaseUri, domain); } } } } }
public MySqlJobQueue(MySqlStorage storage, MySqlStorageOptions options) { if (storage == null) { throw new ArgumentNullException("storage"); } if (options == null) { throw new ArgumentNullException("options"); } _storage = storage; _options = options; }
private void LoadConfig() { IniReader config = IniReader.FromLocation(RootLocation.AllUserConfig); this.LogInfo("Loading {0}", config); imscpConfig = config.ReadStruct <ImscpConfig>("Imscp", true); if (imscpConfig.Hostname == null || imscpConfig.Hostname.EndsWith(".")) { throw new Exception(string.Format("Invalid hostname {0}", imscpConfig.Hostname)); } foreach (string section in config.ReadSection("InternetX", true)) { this.LogDebug("Loading InternetX account <cyan>{0}", section); InternetXConfig internetXConfig = config.ReadStruct <InternetXConfig>(section, true); autodnsAccounts.Add(new Autodns(internetXConfig)); this.LogInfo("Loaded InternetX account <green>{0}", section); } var cs = new ConnectionString("mysql", imscpConfig.UserName, imscpConfig.Password, imscpConfig.Database); var storage = new MySqlStorage(cs, DbConnectionOptions.AllowUnsafeConnections); imscp = storage.GetDatabase("imscp", false); imscpDomain = new ReadCachedTable <Domain>(imscp.GetTable <Domain>()); this.LogDebug("Loaded {0}", imscpDomain); imscpSubdomain = new ReadCachedTable <Subdomain>(imscp.GetTable <Subdomain>()); this.LogDebug("Loaded {0}", imscpSubdomain); imscpDomainDns = new ReadCachedTable <DomainDns>(imscp.GetTable <DomainDns>()); this.LogDebug("Loaded {0}", imscpDomainDns); imscpAdmins = new ReadCachedTable <Admin>(imscp.GetTable <Admin>()); this.LogDebug("Loaded {0}", imscpAdmins); #region MAIL string server = config.ReadSetting("MAIL", "SERVER"); m_MailSender = config.ReadSetting("MAIL", "SENDER"); if (string.IsNullOrEmpty(server)) { server = "localhost"; } m_SmtpClient = new SmtpClient(server); string username = config.ReadSetting("MAIL", "USERNAME"); string password = config.ReadSetting("MAIL", "PASSWORD"); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { m_SmtpClient.Credentials = new NetworkCredential(username, password); } m_SmtpClient.Send(m_MailSender, "*****@*****.**", "CaveSystems AutoDNS", "AutoDNS restarted."); #endregion }
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); }
public MySqlFetchedJob( MySqlStorage storage, IDbConnection connection, FetchedJob fetchedJob) { if (fetchedJob == null) { throw new ArgumentNullException("fetchedJob"); } _storage = storage ?? throw new ArgumentNullException("storage"); _connection = connection ?? throw new ArgumentNullException("connection"); _id = fetchedJob.Id; JobId = fetchedJob.JobId.ToString(CultureInfo.InvariantCulture); Queue = fetchedJob.Queue; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); #region swagger services.AddSwaggerGen(p => { p.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Version = "v1", Title = "WishSalesCenter API 接口文档", Contact = new OpenApiContact { Name = "qinguoyong", Email = "*****@*****.**", Url = new Uri("http://xxxx.com"), }, }); // 为 Swagger JSON and UI设置xml文档注释路径 var xmlPathByModel = Path.Combine(AppContext.BaseDirectory, "Qingy.DotNetCoreStudy.HangfireManagement.xml"); p.IncludeXmlComments(xmlPathByModel); // c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader参数 }); #endregion services.AddDbContext <HangfireTaskContext>(p => p.UseMySql(Configuration.GetConnectionString("TimingTaskConnection"))); services.AddHttpClient(); //注入HttpClient var storage = new MySqlStorage(Configuration.GetConnectionString("TimingTaskConnection") , new MySqlStorageOptions { PrepareSchemaIfNecessary = true, TablePrefix = "" }); //GlobalConfiguration.Configuration.UseStorage(new MySqlStorage(storage, new MySqlStorageOptions //{ // TransactionIsolationLevel = IsolationLevel.ReadCommitted, // 事务隔离级别。默认值为读提交。 // QueuePollInterval = 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分钟 //})); //hangfire services.AddHangfire(p => p.UseStorage(storage)); }
public override async Task Init() { var services = new ServiceCollection(); services.AddOptions(); services.AddLogging(); services.Configure <MySqlStorageOptions>(o => { o.ConnectionString = "DataBase=HttpReports;Data Source=localhost;User Id=root;Password=123456"; }); services.AddTransient <MySqlStorage>(); services.AddSingleton <MySqlConnectionFactory>(); _storage = services.BuildServiceProvider().GetRequiredService <MySqlStorage>(); await _storage.InitAsync(); }
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); }
/// <summary> /// 配置Hangfire /// </summary> /// <param name="app"></param> public void ConfigureHangfire(IAppBuilder app) { JobIocConfig.Register(); //Hangfire IOC配置 GlobalConfiguration.Configuration.UseActivator(new SimpleInjectorJobActivator(JobIocConfig.Container)); //hangfire 配置 var jobConnection = ConfigurationManager.ConnectionStrings["JuCheap-Job"]; if (jobConnection.ProviderName.IsEqual("System.Data.SqlClient"))//使用SQLServer作为 数据库存储 { var storage = new SqlServerStorage("JuCheap-Job"); GlobalConfiguration.Configuration.UseStorage(storage).UseConsole(); } else if (jobConnection.ProviderName.IsEqual("MySql.Data.MySqlClient"))//使用MySql作为 数据库存储 { var storage = new MySqlStorage("JuCheap-Job"); GlobalConfiguration.Configuration.UseStorage(storage).UseConsole(); } GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 }); //OWIN-based authentication var options = new DashboardOptions { Authorization = new[] { new HangfireAuthorizationFilter() } }; app.UseHangfireDashboard("/taskcenter", options); LoadRecurringTasks(); var jobOptions = new BackgroundJobServerOptions { ServerName = Environment.MachineName }; app.UseHangfireServer(jobOptions); }
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; }
private static void DoShit2() { var i = 1; var cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler { CookieContainer = cookieContainer }) { using (var client = new HttpClient(handler)) { using (var mySql = new MySqlStorage()) { foreach (var abbreviation in mySql.GetAll <AbbreviationEntity>().OrderBy(x => x.Decryption?.Length ?? 0)) { if (string.IsNullOrEmpty(abbreviation.Decryption)) { continue; } var response = client.GetAsync( abbreviation.Link) .GetAwaiter() .GetResult(); var html = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); var config = Configuration.Default; var context = BrowsingContext.New(config); var document = context.OpenAsync(req => req.Content(html)).Result; var div = document.GetElementsByClassName("mw-parser-output").Single(); var ol = div.Children .SkipWhile(x => x.TagName != "H4" || !x.Children.Any(z => z.TagName == "SPAN" && z.Id == "Значение")) .Skip(1) .FirstOrDefault(x => x.TagName == "OL"); abbreviation.Decryption = ol?.TextContent; mySql.InsertOrUpdate(abbreviation); } } } } }
public override async Task Init() { var services = new ServiceCollection(); services.AddOptions(); services.AddLogging(); services.Configure <MySqlStorageOptions>(o => { o.ConnectionString = "Data Source=127.0.0.1;Initial Catalog=HttpReports;User ID=test;Password=test;charset=utf8;SslMode=none;"; o.DeferSecond = 3; o.DeferThreshold = 5; o.EnableDefer = true; }); services.AddTransient <MySqlStorage>(); services.AddSingleton <MySqlConnectionFactory>(); _storage = services.BuildServiceProvider().GetRequiredService <MySqlStorage>(); await _storage.InitAsync(); }
// 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) { 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); services.AddHangfire(config => config.UseStorage(storage)); services.AddHangfireServer(); services.AddControllers(); }
/// <summary>Faz o registro de metricas no serviço DI</summary> /// <param name="services">Serviço DI</param> /// <param name="configuration">Configurações do sistema</param> public static IServiceCollection AddRegisterHangFire(this IServiceCollection services, IConfiguration configuration) { MySqlStorageOptions mySqlStorageOptions = new MySqlStorageOptions(); configuration.GetSection("Hangfire:MySqlStorageOptions").Bind(mySqlStorageOptions); var storage = new MySqlStorage( configuration.GetValue <string>("Hangfire:ConnectionStrings:hangfiredb"), mySqlStorageOptions ); services.AddHangfire( (provider, config) => { config .UseStorage(storage) .UseSerilogLogProvider() .UseFilter(new HangFireLogStepsAttribute(provider.GetRequiredService <ILogger <HangFireLogStepsAttribute> >())); }); return(services); }
public async Task ExecuteAsync() { var storage = new MySqlStorage(AppSettings.ConnectionStrings); //if (AppSettings.EnableDb == "MySql") //{ // var storage = new MySqlStorage(AppSettings.ConnectionStrings); // service.UseDataSynchronizationjob(storage); //} var _storage = storage as MySqlStorage; GlobalConfiguration.Configuration.UseStorage(storage as MySqlStorage); RecurringJob.AddOrUpdate(() => Console.WriteLine("Hangfire AddOrUpdate任务"), "1/5 * * * * *", TimeZoneInfo.Local, "queue1"); BackgroundJobServer jobServer = new BackgroundJobServer(new BackgroundJobServerOptions() { Queues = new string[] { "queue1", "queue2" }, ServerName = "ControlCenterServices", WorkerCount = 1 }, _storage); await jobServer.WaitForShutdownAsync(CancellationToken.None); }
public static void Load() { MySqlStorage storage = new MySqlStorage($"Server={SettingsManager.Configuration.HangfireHost};" + $"Database={SettingsManager.Configuration.HangfireDatabase};" + $"Uid={SettingsManager.Configuration.HangfireUsername};" + $"Pwd={SettingsManager.Configuration.HangfirePassword};" + $"AllowUserVariables=true;"); GlobalConfiguration.Configuration.SetDataCompatibilityLevel(CompatibilityLevel.Version_170); GlobalConfiguration.Configuration.UseSimpleAssemblyNameTypeSerializer(); GlobalConfiguration.Configuration.UseRecommendedSerializerSettings(); // TODO Better way to log hangfire, it spams messages //GlobalConfiguration.Configuration.UseNLogLogProvider(); GlobalConfiguration.Configuration.UseStorage(storage); _ = new BackgroundJobServer(new BackgroundJobServerOptions { SchedulePollingInterval = TimeSpan.FromSeconds(10), Queues = Queues.All }); LoggingManager.Log.Info("Complete"); }
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 mySqlStorageMock = new Mock <MySqlStorage>(_connection); mySqlStorageMock .Setup(m => m.QueueProviders) .Returns(new PersistentJobQueueProviderCollection(defaultProviderMock.Object)); _storage = mySqlStorageMock.Object; _sut = new MySqlMonitoringApi(_storage, _jobListLimit); }
public override void PreConfigureServices(ServiceConfigurationContext context) { var configuration = context.Services.GetConfiguration(); var mysqlStorageOptions = new MySqlStorageOptions(); configuration.GetSection("Hangfire:MySql").Bind(mysqlStorageOptions); var hangfireMySqlConfiguration = configuration.GetSection("Hangfire:MySql:Connection"); var hangfireMySqlCon = hangfireMySqlConfiguration.Exists() ? hangfireMySqlConfiguration.Value : configuration.GetConnectionString("Default"); _jobStorage = new MySqlStorage(hangfireMySqlCon, mysqlStorageOptions); context.Services.AddSingleton <JobStorage, MySqlStorage>(fac => { return(_jobStorage); }); PreConfigure <IGlobalConfiguration>(config => { config.UseStorage(_jobStorage); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddHealthChecks() .AddCheck <BetDetailServiceHealthCheck>("BetDetailServiceHealthCheck", failureStatus: HealthStatus.Degraded, tags: new[] { "example" }); var storage = new MySqlStorage(AppSettings.Settings.HangfireConnection, new MySqlStorageOptions { TransactionIsolationLevel = System.Data.IsolationLevel.ReadCommitted, QueuePollInterval = TimeSpan.FromSeconds(15), JobExpirationCheckInterval = TimeSpan.FromHours(1), CountersAggregateInterval = TimeSpan.FromMinutes(5), PrepareSchemaIfNecessary = true, DashboardJobListLimit = 50000, TransactionTimeout = TimeSpan.FromMinutes(1), TablePrefix = "Hangfire" }); services.AddHangfire(configuration => configuration.UseStorage(storage)); services.AddHangfireServer(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add ExchangeSettings so it can be injected in controllers services.Configure <GeneralSettings>(options => Configuration.GetSection("General").Bind(options)); services.Configure <ExchangeSettings>(options => Configuration.GetSection("Exchange").Bind(options)); services.Configure <WalletSettings>(options => Configuration.GetSection("Wallet").Bind(options)); services.Configure <EmailSenderSettings>(options => Configuration.GetSection("EmailSender").Bind(options)); services.Configure <ApiSettings>(options => Configuration.GetSection("Api").Bind(options)); services.Configure <KycSettings>(options => Configuration.GetSection("Kyc").Bind(options)); services.Configure <TripwireSettings>(options => Configuration.GetSection("Tripwire").Bind(options)); services.Configure <FiatProcessorSettings>(options => Configuration.GetSection("FiatProcessor").Bind(options)); services.AddDbContext <ApplicationDbContext>(options => options.UseLazyLoadingProxies() .UseMySql(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); services.ConfigureApplicationCookie(options => { // use our efcore ticket store options.ExpireTimeSpan = TimeSpan.FromDays(14); options.SlidingExpiration = true; options.SessionStore = new EfTicketStore(services.BuildServiceProvider()); // set our session cookie security policy options.Cookie.HttpOnly = true; options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax; options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest; }); services.AddAntiforgery(options => { // set our CSRF cookie security policy options.Cookie.HttpOnly = true; options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict; options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest; }); // catch exception which happens if the database does not yet exist because of migrations still in the process of being applied try { // add hangfire service (using out mysql db) var storage = new MySqlStorage(Configuration.GetConnectionString("DefaultConnection"), new MySqlStorageOptions { TablePrefix = "Hangfire" }); services.AddHangfire(x => x.UseStorage(storage)); } catch { Console.WriteLine("Failed to add hangfire! App will fail unless we are just doing design time stuff (migrations etc)"); } // Add application services. services.AddTransient <IEmailSender, EmailSender>(); services.AddSingleton <IWebsocketTokens, WebsocketTokens>(); services.AddSingleton <IWalletProvider, WalletProvider>(); services.AddTransient <IBroker, viafront3.Services.Broker>(); services.AddSingleton <ITripwire, Tripwire>(); services.AddSingleton <IDepositsWithdrawals, DepositsWithdrawals>(); services.AddSingleton <IUserLocks, UserLocks>(); services.AddTransient <IAppVersion, AppVersion>(); services.AddMvc(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())); System.ComponentModel.TypeDescriptor.AddAttributes(typeof(DateTime), new System.ComponentModel.TypeConverterAttribute(typeof(NzDateTimeConverter))); }
public MySqlDistributedLock(MySqlStorage storage, string resource, TimeSpan timeout) : this(storage.CreateAndOpenConnection(), resource, timeout) { _storage = storage; }
private static MySqlJobQueue CreateJobQueue(MySqlConnection connection) { var storage = new MySqlStorage(connection); return(new MySqlJobQueue(storage, new MySqlStorageOptions())); }
public MySqlJobQueueTests() { _connection = ConnectionUtils.CreateConnection(); _storage = new MySqlStorage(_connection); }
public MySqlJobQueueMonitoringApi(MySqlStorage storage) { if (storage == null) throw new ArgumentNullException("storage"); _storage = storage; }
public MySqlJobQueue(MySqlStorage storage, MySqlStorageOptions options) { _storage = storage ?? throw new ArgumentNullException("storage"); _options = options ?? throw new ArgumentNullException("options"); }
public MySqlMonitoringApi(IStorage storage, IOptions <MySqlOptions> options) { _storage = storage as MySqlStorage ?? throw new ArgumentNullException(nameof(storage)); _prefix = options.Value.TableNamePrefix ?? throw new ArgumentNullException(nameof(options)); }
public CountersAggregatorTests() { _connection = ConnectionUtils.CreateConnection(); _storage = new MySqlStorage(_connection); _sut = new CountersAggregator(_storage, TimeSpan.Zero); }
public MySqlDistributedLock(MySqlStorage storage, MySqlStorageOptions options, string resource, TimeSpan timeout) : this(storage.CreateAndOpenConnection(), options, resource, timeout) { _storage = storage; }
public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //将默认xml返回数据格式改为json config.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json")); app.UseWebApi(config); //HangFire配置 bool isTaskRun = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["IsTaskRun"]); if (!isTaskRun) { return; } string hangFireType = System.Configuration.ConfigurationManager.AppSettings["HangFireStoreType"]; if (hangFireType == "SqlServer") { //SqlServer数据库 GlobalConfiguration.Configuration .UseSqlServerStorage("HangFireCon").UseConsole(); //.UseRecurringJob(typeof(RecurringJobService)).UseDefaultActivator(); //GlobalConfiguration.Configuration.UseRecurringJob("recurringjob.json"); } else if (hangFireType == "MySql") { //MySql数据库 MySqlStorage mySqlS = new MySqlStorage("HangFireCon", 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), }); GlobalConfiguration.Configuration .UseStorage(mySqlS).UseConsole(); //.UseRecurringJob(typeof(RecurringJobService)).UseDefaultActivator(); //配置文件 //x.UseRecurringJob("recurringjob.json"); } else if (hangFireType == "Redis") { Redis = ConnectionMultiplexer.Connect(System.Configuration.ConfigurationManager.ConnectionStrings["HangFireCon"].ConnectionString); GlobalConfiguration.Configuration .UseRedisStorage(Redis).UseConsole(). UseRecurringJob(typeof(RecurringJobService)).UseDefaultActivator(); } app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new HangFireAuthorizationFilter() }, }); app.UseHangfireServer(new BackgroundJobServerOptions { Queues = new[] { "default", "apis", "jobs" } }); //测试 //BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget")); //BackgroundJob.Schedule(() => Console.WriteLine("Delayed"), TimeSpan.FromDays(1)); //RecurringJob.AddOrUpdate(() => Console.WriteLine("Daily Job"), Cron.Daily); //string cron = string.Empty; //RecurringJob.AddOrUpdate<IThumbnailInitialize>(string.Format("图层与地图初始化下载"), x => x.ExcuteJob(null), Cron.Daily, TimeZoneInfo.Local); BackgroundJob.Enqueue <ThumbnailInitialize>(x => x.ExcuteJob(null)); }
private ExpirationManager CreateManager(MySqlConnection connection) { var storage = new MySqlStorage(connection); return(new ExpirationManager(storage, TimeSpan.Zero)); }
public ExpirationManager(MySqlStorage storage) : this(storage, TimeSpan.FromHours(1)) { }
public AccountStorage(IConfigurationProvider <RealmServerConfiguration> configurationProvider) { this.configurationProvider = configurationProvider; mySqlStorage = new MySqlStorage(); }