Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch Microsoft.Extensions.Caching.Redis connection fail?

I need to use Microsoft.Extensions.Caching.Redis into my asp.net core project.

I put this code into ConfigureService (Startup.cs):

IDistributedCache cache = new RedisCache(new RedisCacheOptions
{
    Configuration = Configuration.GetConnectionString("Redis"),
    InstanceName = "Master"
});

services.AddSingleton<IDistributedCache>(cache);

What I need is to catch a connection exception (in case the Redis server is down, or the server is not reachable), but I haven't found a method to check connection and if I wrap code into a try/catch nothing happens.

Is there a way to accomplish my task?

Thanks

like image 308
tore Avatar asked Sep 12 '26 22:09

tore


1 Answers

At this step you haven't opened a connection to Redis yet, you only created an instance of RedisCache class.

The connection will be opened later when you will use public methods of the class. Something like RedisCache.GetAsync method as the example:

// IDistributedCache  _cache;
// ...
// This is the place where you may get the exception
var value = await _cache.GetAsync(key);

Here connection will be created internally (if needed) using private Connect methods.

like image 198
Set Avatar answered Sep 15 '26 11:09

Set



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!