Skip to content

ephemerally.redis

Colton Fussy edited this page Jun 21, 2024 · 5 revisions

Redis

dotnet add package Ephemerally.Redis

The fixed number of databases in a Redis instance creates a challenge for using them in an ephemeral way. To overcome this, certain high-level Ephemerally types like EphemeralConnectionMultiplexer internally employ a mechanism to control exclusive access to each database called FixedSizeObjectPool. It is recommended to use the high-level components rather than dealing with the Redis databases directly.

If using in tests, check out Ephemerally.Redis.Xunit for premade fixtures.

IConnectionMultiplexer

✔️ recommended

// Start with a regular multiplexer (do not use elsewhere*)
IConnectionMultiplexer standardMultiplexer = ConnectionMultiplexer.ConnectAsync(...);

// Use it to create an ephemeral multiplexer
//     (a single instance should be reused everywhere per Redis instance/cluster)
await using IConnectionMultiplexer ephemeralMultiplexer = standardMultiplexer.ToEphemeralMultiplexer();
// .AsEphemeralMultiplexer() is also available if you think you might
//     already have an EphemeralConnectionMultiplexer instance behind IConnectionMultiplexer

// Get databases from the ephemeral multiplexer ONLY*
await using var db0 = ephemeralMultiplexer.GetEphemeralDatabase();

* EphemeralConnectionMultiplexer instances can be configured to use a specific set of databases. In these cases it is safe to use another multiplexer to access other databases not given to the EphemeralConnectionMultiplexer, but it is important to not overlap usage and allow the EphemeralConnectionMultiplexer exclusive access to its set of databases.

IDatabase

❌ not recommended

// Get a database and make it ephemeral
await using var database = connectionMultiplexer.GetEphemeralDatabase();
// Make an existing database ephemeral
IDatabase existingDatabase = connectionMultiplexer.GetDatabase();
await using var ephemeralExistingDatabase.ToEphemeral();
// .AsEphemeral() is also available if you think you might
//     already have an EphemeralRedisDatabase instance behind IDatabase