MichaCo / CacheManager

CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features.
http://cachemanager.michaco.net
Apache License 2.0
2.33k stars 457 forks source link

CacheManager.Core throws exception if redis is unavailable #328

Closed subhendu-de closed 3 years ago

subhendu-de commented 3 years ago

We are using CacheManager.Core, CacheManager.StackExchange.Redis and CacheManager.Microsoft.Extensions.Caching.Memory. Following codesnippet is used to configure

ICacheManagerConfiguration cacheManagerConfig = new ConfigurationBuilder("CachedData")
.WithMicrosoftLogging(loggerFactory)
.WithJsonSerializer()
.WithMicrosoftMemoryCacheHandle("CachedData.In-memory")
.WithExpiration(ExpirationMode.Absolute, expiration)
.And
.WithRedisConfiguration("CachedData.Redis", redisConnectionString, enableKeyspaceNotifications: true)
.WithRedisCacheHandle("CachedData.Redis")
.WithExpiration(ExpirationMode.Absolute, expiration)
.And
.WithRedisBackplane("CachedData.Redis")
.Build();

If the redis is unavailable, it throws exceptions. Is there a way to configure so that it can start using in-memory cache when redis is unavailable?

MichaCo commented 3 years ago

no, that's by design. if you want to use Redis, you have to have Redis available ^^

Also, the moment you add a backplane, the library has to setup listeners for the events send/received from Redis' Pub/Sub. That has to happen at setup time, there is no other way really to do that later.

subhendu-de commented 3 years ago

Thanks @MichaCo!

I'm thinking to refer cacheManager as null in case redis is unavailable during startup. Also handle the exception gracefully at the consuming code.

ICacheManager<int> cacheManager = null;
int result = null;

ICacheManagerConfiguration cacheManagerConfig = new ConfigurationBuilder("CachedData")
.WithMicrosoftLogging(loggerFactory)
.WithJsonSerializer()
.And
.WithRedisConfiguration("CachedData.Redis", redisConnectionString, enableKeyspaceNotifications: true)
.WithRedisCacheHandle("CachedData.Redis")
.WithExpiration(ExpirationMode.Absolute, expiration)
.And
.WithRedisBackplane("CachedData.Redis")
.Build();

try
{
cacheManager = CacheFactory.FromConfiguration<int>(cacheManagerConfig);
result = cacheManager.Get(key);
}
catch
{
logger.log("Error in connecting to redis");
result = serviceManager.Get(key)
}
MichaCo commented 3 years ago

Sure, only comment on your code example, don't create a new CacheManager instance every time you want to get or set a key. That would not work, the instance has to be a singleton.