diff --git a/Core.Blueprint.Redis/Configuration/RegisterBlueprint.cs b/Core.Blueprint.Redis/Configuration/RegisterBlueprint.cs index 3aeb596..979c898 100644 --- a/Core.Blueprint.Redis/Configuration/RegisterBlueprint.cs +++ b/Core.Blueprint.Redis/Configuration/RegisterBlueprint.cs @@ -27,7 +27,7 @@ namespace Core.Blueprint.Redis.Configuration // Register RedisCacheProvider services.AddSingleton(provider => - new RedisCacheProvider(redisConnectionString, provider.GetRequiredService>())); + new RedisCacheProvider(redisConnectionString, provider.GetRequiredService>(), configuration)); // Get CacheSettings and register with the ICacheSettings interface var cacheSettings = configuration.GetSection("CacheSettings").Get(); diff --git a/Core.Blueprint.Redis/RedisCacheProvider.cs b/Core.Blueprint.Redis/RedisCacheProvider.cs index 47a275d..5d8c6e2 100644 --- a/Core.Blueprint.Redis/RedisCacheProvider.cs +++ b/Core.Blueprint.Redis/RedisCacheProvider.cs @@ -1,7 +1,7 @@ using Azure.Identity; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using StackExchange.Redis; -using System; using System.Text.Json; namespace Core.Blueprint.Redis @@ -13,6 +13,7 @@ namespace Core.Blueprint.Redis { private IDatabase _cacheDatabase = null!; private readonly ILogger _logger; + private readonly bool _useRedis; /// /// Initializes a new instance of the class. @@ -20,12 +21,13 @@ namespace Core.Blueprint.Redis /// The Redis connection string. /// The logger instance for logging operations. /// Thrown when connection string is null or empty. - public RedisCacheProvider(string connectionString, ILogger logger) + public RedisCacheProvider(string connectionString, ILogger logger, IConfiguration configuration) { if (string.IsNullOrWhiteSpace(connectionString)) throw new ArgumentNullException(nameof(connectionString), "Redis connection string cannot be null or empty."); _logger = logger; + _useRedis = configuration.GetValue("UseRedisCache", false); _cacheDatabase = InitializeRedisAsync(connectionString).GetAwaiter().GetResult(); } @@ -36,30 +38,35 @@ namespace Core.Blueprint.Redis /// The Redis connection string. /// An instance representing the Redis cache database. /// Thrown when the connection to Redis fails. - async Task InitializeRedisAsync(string connectionString) + async Task InitializeRedisAsync(string connectionString) { try { - var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty; - ConnectionMultiplexer connectionMultiplexer; - - if (environment.Equals("Local", StringComparison.OrdinalIgnoreCase)) + if (_useRedis) { - connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(connectionString); - } - else - { - var configurationOptions = await ConfigurationOptions.Parse(connectionString) - .ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential()); + var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty; + ConnectionMultiplexer connectionMultiplexer; - configurationOptions.AbortOnConnectFail = false; + if (environment.Equals("Local", StringComparison.OrdinalIgnoreCase)) + { + connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(connectionString); + } + else + { + var configurationOptions = await ConfigurationOptions.Parse(connectionString) + .ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential()); - connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions); + configurationOptions.AbortOnConnectFail = false; + + connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions); + } + + _logger.LogInformation("Successfully connected to Redis."); + + return connectionMultiplexer.GetDatabase(); } - _logger.LogInformation("Successfully connected to Redis."); - - return connectionMultiplexer.GetDatabase(); + return null; } catch (Exception ex) { @@ -78,15 +85,21 @@ namespace Core.Blueprint.Redis { try { - var value = await _cacheDatabase.StringGetAsync(key); - if (value.IsNullOrEmpty) + if (_useRedis is not false) { - _logger.LogInformation($"Cache miss for key: {key}"); - return default; + var value = await _cacheDatabase.StringGetAsync(key); + + if (value.IsNullOrEmpty) + { + _logger.LogInformation($"Cache miss for key: {key}"); + return default; + } + + _logger.LogInformation($"Cache hit for key: {key}"); + return JsonSerializer.Deserialize(value); } - _logger.LogInformation($"Cache hit for key: {key}"); - return JsonSerializer.Deserialize(value); + return default; } catch (Exception ex) { @@ -105,9 +118,12 @@ namespace Core.Blueprint.Redis { try { - var json = JsonSerializer.Serialize(value); - await _cacheDatabase.StringSetAsync(key, json, expiry); - _logger.LogInformation($"Cache item set with key: {key}"); + if (_useRedis is not false) + { + var json = JsonSerializer.Serialize(value); + await _cacheDatabase.StringSetAsync(key, json, expiry); + _logger.LogInformation($"Cache item set with key: {key}"); + } } catch (Exception ex) { @@ -124,8 +140,11 @@ namespace Core.Blueprint.Redis { try { - await _cacheDatabase.KeyDeleteAsync(key); - _logger.LogInformation($"Cache item removed with key: {key}"); + if (_useRedis is not false) + { + await _cacheDatabase.KeyDeleteAsync(key); + _logger.LogInformation($"Cache item removed with key: {key}"); + } } catch (Exception ex) { @@ -143,9 +162,13 @@ namespace Core.Blueprint.Redis { try { - var exists = await _cacheDatabase.KeyExistsAsync(key); - _logger.LogInformation($"Cache item exists check for key: {key} - {exists}"); - return exists; + if (_useRedis is not false) + { + var exists = await _cacheDatabase.KeyExistsAsync(key); + _logger.LogInformation($"Cache item exists check for key: {key} - {exists}"); + } + + return false; } catch (Exception ex) { @@ -163,15 +186,18 @@ namespace Core.Blueprint.Redis { try { - var value = await _cacheDatabase.StringGetAsync(key); - if (!value.IsNullOrEmpty) + if (_useRedis is not false) { - await _cacheDatabase.StringSetAsync(key, value, expiry); - _logger.LogInformation($"Cache item refreshed with key: {key}"); - } - else - { - _logger.LogWarning($"Cache item with key: {key} does not exist, cannot refresh"); + var value = await _cacheDatabase.StringGetAsync(key); + if (!value.IsNullOrEmpty) + { + await _cacheDatabase.StringSetAsync(key, value, expiry); + _logger.LogInformation($"Cache item refreshed with key: {key}"); + } + else + { + _logger.LogWarning($"Cache item with key: {key} does not exist, cannot refresh"); + } } } catch (Exception ex)