Introduction to Hangfire.Redis.StackExchange
Overview
Hangfire.Redis.StackExchange is a Hangfire Redis storage solution, crafted with the efficiency of the StackExchange.Redis client. This project extends the capabilities of Hangfire.Redis by integrating the robust StackExchange.Redis into job processing configurations.
Key Features
- Hangfire Batches Support: Full support for Hangfire Batches, effective in organizing multiple background tasks.
- Resource Efficiency: Optimized usage of Redis resources using ConnectionMultiplexer.
- Redis Prefix Support: Enables multiple Hangfire instances to operate against a single Redis database seamlessly.
- Customizable Lists: Users can adjust the size of 'Succeeded' and 'Failed' job lists.
Note: The
Hangfire.Redis.StackExchange.StrongName
package is not signed asHangfire.Core
lacks a signature.
Tutorial: Setting up Hangfire on Redis in ASP.NET Core MVC
Getting Started
To integrate Hangfire with Redis in an ASP.NET Core MVC project, install the packages Hangfire.AspNetCore
and Hangfire.Redis.StackExchange
. The setup in Startup.cs
requires the following basic configuration:
public class Startup
{
public static ConnectionMultiplexer Redis;
public Startup(IHostingEnvironment env)
{
Redis = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("Redis"));
}
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(configuration =>
{
configuration.UseRedisStorage(Redis);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseHangfireServer();
}
}
Note: If utilizing the
Microsoft.Extensions.Caching.Redis
package, replaceHangfire.Redis.StackExchange
withHangfire.Redis.StackExchange.StrongName
.
Configuration Options
Redis Storage Configuration
The configuration.UseRedisStorage(...)
method accepts:
-
A Redis connection string or a
ConnectionMultiplexer
object. It's advised to utilize a singleConnectionMultiplexer
for optimal reuse. -
A
RedisStorageOptions
object that offers settings such asInvisibilityTimeout
,FetchTimeout
, and importantly, thePrefix
property to differentiate project instances on the same Redis database.
Server Configuration
The app.UseHangfireServer(...)
method utilizes BackgroundJobServerOptions
to set server properties like ServerName
, WorkerCount
, and various interval configurations to optimize CPU usage.
Implementing the Hangfire Dashboard
To set up a Hangfire dashboard in ASP.NET Core MVC, particularly for users with the Administrator
role, the following snippet showcases the process:
public class AdministratorHangfireDashboardAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var user = context.GetHttpContext().User;
return user.Identity.IsAuthenticated && user.IsInRole("Administrator");
}
}
Integrate it in your application as follows:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCookieAuthentication(...);
app.UseHangfireDashboard(options: new DashboardOptions
{
Authorization = new[] { new AdministratorHangfireDashboardAuthorizationFilter() }
});
}
Developing Jobs with Dependency Injection
Define jobs within classes that are registered via ASP.NET Core's dependency injection, thereby enabling access to other services, such as DbContext
:
public class MyHangfireJobs
{
public async Task SendGetRequest()
{
var client = new HttpClient();
await client.GetAsync("https://www.accelist.com");
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MyHangfireJobs>();
}
Jobs can then be executed using expressions to enqueue, schedule, or set up recurring jobs:
BackgroundJob.Enqueue<MyHangfireJobs>(jobs => jobs.SendGetRequest());
BackgroundJob.Schedule<MyHangfireJobs>(jobs => jobs.SendGetRequest(), DateTimeOffset.UtcNow.AddDays(1));
RecurringJob.AddOrUpdate<MyHangfireJobs>("RecurringSendGetRequest", jobs => jobs.SendGetRequest(), Cron.Hourly());
This comprehensive solution empowers developers to efficiently manage background jobs within Redis environments using Hangfire in .NET applications.