Skip to content
This repository was archived by the owner on Dec 14, 2018. It is now read-only.

Allow selecting database number and use existing IConnectionMultiplexer #318

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions src/Microsoft.Extensions.Caching.Redis/RedisCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class RedisCache : IDistributedCache, IDisposable
private const string DataKey = "data";
private const long NotPresent = -1;

private volatile ConnectionMultiplexer _connection;
private volatile IConnectionMultiplexer _connection;
private IDatabase _cache;

private readonly RedisCacheOptions _options;
Expand All @@ -50,6 +50,16 @@ public RedisCache(IOptions<RedisCacheOptions> optionsAccessor)
_instance = _options.InstanceName ?? string.Empty;
}

public RedisCache(IOptions<RedisCacheOptions> optionsAccessor, IConnectionMultiplexer connection):this(optionsAccessor)
{
if (connection == null)
{
throw new ArgumentNullException(nameof(connection));
}

_connection = connection;
}

public byte[] Get(string key)
{
if (key == null)
Expand Down Expand Up @@ -164,7 +174,7 @@ public void Refresh(string key)

private void Connect()
{
if (_connection != null)
if (_connection != null && _cache == null)
{
return;
}
Expand All @@ -175,7 +185,11 @@ private void Connect()
if (_connection == null)
{
_connection = ConnectionMultiplexer.Connect(_options.Configuration);
_cache = _connection.GetDatabase();

}
if (_cache == null)
{
_cache = _connection.GetDatabase(_options.Database ?? 0);
}
}
finally
Expand All @@ -188,7 +202,7 @@ private void Connect()
{
token.ThrowIfCancellationRequested();

if (_connection != null)
if (_connection != null && _cache == null)
{
return;
}
Expand All @@ -199,7 +213,11 @@ private void Connect()
if (_connection == null)
{
_connection = await ConnectionMultiplexer.ConnectAsync(_options.Configuration);
_cache = _connection.GetDatabase();

}
if (_cache == null)
{
_cache = _connection.GetDatabase(_options.Database??0);
}
}
finally
Expand Down
5 changes: 5 additions & 0 deletions src/Microsoft.Extensions.Caching.Redis/RedisCacheOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ public class RedisCacheOptions : IOptions<RedisCacheOptions>
/// </summary>
public string Configuration { get; set; }

/// <summary>
/// The database to be used
/// </summary>
public int? Database { get; set; }

/// <summary>
/// The Redis instance name.
/// </summary>
Expand Down