Using Redis¶

Hangfire Pro subscription required

Starting from Hangfire 1.2, this feature is a part of Hangfire Pro package set

Hangfire with Redis job storage implementation processes jobs much faster than with SQL Server storage. On my development machine I observed more than 4x throughput improvement with empty jobs (method that does not do anything). Hangfire.Pro.Redis leverages the BRPOPLPUSH command to fetch jobs, so the job processing latency is kept to minimum.
Using Redis - 图1
Please, see the downloads page to obtain latest version of Redis. If you unfamiliar with this great storage, please see its documentation. Binaries for Windows are available through NuGet (32-bit, 64-bit) and Chocolatey galleries (64-bit only).

Limitations¶

Multiple Redis endpoints are only supported in Redis Cluster configuration starting from Hangfire.Pro.Redis 2.1.0. You can’t use multiple detached masters or Redis Sentinel configurations.

Redis Configuration¶

Please read the official Redis documentation to learn how to configure it, especially Redis Persistence and Redis Administration sections to get started with the fundamentals. The following options should be configured to run your background jobs smoothly.

Ensure the following options are configured

These values are default for on-premise Redis installations, but other environments may have different defaults, for example Azure Redis Cache and AWS ElastiCache**use non-compatible settings** by default.

  1. # Non-zero value cause long-running background jobs to be
  2. # processed multiple times due to connection was closed.
  3. # NOTE: This setting is only required for Hangfire.Pro.Redis 1.x!
  4. timeout 0
  5.  
  6. # Hangfire neither expect that non-expired keys are deleted,
  7. # nor expiring keys are evicted before the expiration time.
  8. maxmemory-policy noeviction

Hangfire.Pro.Redis 2.x¶

Redis ≥ 2.6.12 is required

Installation¶

Ensure that you have configured the private Hangfire Pro NuGet feed as written here, and use your favorite NuGet client to install the Hangfire.Pro.Redis package:

  1. PM> Install-Package Hangfire.Pro.Redis

If your project targets .NET Core, just add a dependency in your project.json file:

  1. "dependencies": {
  2. "Hangfire.Pro.Redis": "2.0.2"
  3. }

Configuration¶

After installing the package, a couple of the UseRedisStorage extension method overloads will be available for the IGlobalConfiguration interface. They allow you to configure Redis job storage, using both configuration string and Hangfire-specific options.

Connection string¶

The basic one is the following, will connect to the Redis on localhost using the default port, database and options:

  1. GlobalConfiguration.Configuration.UseRedisStorage();

For ASP.NET Core projects, call the UseRedisStorage method from the AddHangfire method delegate:

  1. services.AddHangfire(configuration => configuration.UseRedisStorage());

You can customize the connection string using the StackExchange.Redis’ configuration string format. Please read their documentation for details. The values for the following options have their own defaults in Hangfire, but can be overriden in the connection string:

Option Default
syncTimeout 30000
allowAdmin true
  1. GlobalConfiguration.Configuration
  2. .UseRedisStorage("contoso5.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");

In .NET Core you need to use IP addresses instead, because DNS lookup isn’t available in StackExchange.Redis for .NET Core.

  1. GlobalConfiguration.Configuration
  2. .UseRedisStorage("127.0.0.1");

Redis Cluster support¶

You can use a single endpoint to connect to a Redis cluster, Hangfire will detect other instances automatically by querying the node configuration. However, it’s better to pass multiple endpoints in order to mitigate connectivity issues, when some of endpoints aren’t available, e.g. during the failover process.

Since Hangfire requires transactions, and Redis doesn’t support ones that span multiple hash slots, you also need to configure the prefix to assign it to the same hash tag:

  1. GlobalConfiguration.Configuration.UseRedisStorage(
  2. "localhost:6379,localhost:6380,localhost:6381",
  3. new RedisStorageOptions { Prefix = "{hangfire-1}:" });

This will bind all the keys to a single Redis instance. To be able to fully utilize your Redis cluster, consider using multiple JobStorage instances and leveraging some load-balancing technique (round-robin is enough for the most cases). To do so, pick different hash tags for different storages and ensure they are using hash slots that live on different masters by using commands CLUSTER NODES and CLUSTER KEYSLOT.

Passing options¶

You can also pass the Hangfire-specific options for Redis storage by using the RedisStorageOptions class instances:

  1. var options = new RedisStorageOptions
  2. {
  3. Prefix = "hangfire:app1:",
  4. InvisibilityTimeout = TimeSpan.FromHours(3)
  5. };
  6.  
  7. GlobalConfiguration.Configuration.UseRedisStorage("localhost", options);

The following options are available for configuration:

Option Default Description
Database null Redis database number to be used by Hangfire. When null, then the defaultDatabase option from the configuration string is used.
InvisibilityTimeout TimeSpan.FromMinutes(30) Time interval, within which background job is considered to be still successfully processed by a worker. When a timeout is elapsed, another worker will be able to pick the same background job.
Prefix hangfire: Prefix for all Redis keys related to Hangfire.
MaxSucceededListLength 10000 Maximum visible background jobs in the succeeed list to prevent it from growing indefinitely.
MaxDeletedListLength 1000 Maximum visible background jobs in the deleted list to prevent it from growing indefinitely.
SubscriptionIntegrityTimeout TimeSpan.FromHours(1) Timeout for subscription-based fetch. The value should be high enough enough (hours) to decrease the stress on a database. This is an additional layer to provide integrity, because otherwise subscriptions can be active for weeks, and bad things may happen during this time.

Hangfire.Pro.Redis 1.x¶

This is the old version of Redis job storage for Hangfire. It is based on ServiceStack.Redis 3.71, and has no SSL and .NET Core support. No new features will be added for this version. This version is deprecated, switch to the new version to get the new features.

Configuration¶

Hangfire.Pro.Redis package contains some extension methods for the GlobalConfiguration class:

  1. GlobalConfiguration.Configuration
  2. // Use localhost:6379
  3. .UseRedisStorage();
  4. // Using hostname only and default port 6379
  5. .UseRedisStorage("localhost");
  6. // or specify a port
  7. .UseRedisStorage("localhost:6379");
  8. // or add a db number
  9. .UseRedisStorage("localhost:6379", 0);
  10. // or use a password
  11. .UseRedisStorage("password@localhost:6379", 0);
  12.  
  13. // or with options
  14. var options = new RedisStorageOptions();
  15. GlobalConfiguration.Configuration
  16. .UseRedisStorage("localhost", 0, options);

Connection pool size¶

Hangfire leverages connection pool to get connections quickly and shorten their usage. You can configure the pool size to match your environment needs:

  1. var options = new RedisStorageOptions
  2. {
  3. ConnectionPoolSize = 50 // default value
  4. };
  5.  
  6. GlobalConfiguration.Configuration.UseRedisStorage("localhost", 0, options);

Using key prefixes¶

If you are using a shared Redis server for multiple environments, you can specify unique prefix for each environment:

  1. var options = new RedisStorageOptions
  2. {
  3. Prefix = "hangfire:"; // default value
  4. };
  5.  
  6. GlobalConfiguration.Configuration.UseRedisStorage("localhost", 0, options);

原文:

http://docs.hangfire.io/en/latest/configuration/using-redis.html