Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the key difference in using Redis Cache via ConnectionMultiplexer and AddStackExchangeRedisCache(IDistributedCache) in StartUp.cs?

I want to implement Distributed caching(Redis) in ASP.NET Core project. After a bit or research I found that there are two ways of creating a Redis connection using AddStackExchangeRedisCache in Startup.cs and ConnectionMultiplexer

  1. AddStackExchangeRedisCache - This happens in Startup.cs. Doubts in above approach:

  2. Does this work in Prod environment?

  3. When and how the connection is initialized?

  4. Is it thread safe way to create the connection?

  5. By using the ConnectionMultiplexer, we can initialize the DB instance. As per few articles, Lazy initialization will take care of the Thread safety as well

Doubts:

  1. From above approaches, which is the better approach?

I tried both approaches in my local machine both are working fine. But I could not find Pros and Cons of above approach.

like image 534
Ankit Jain Avatar asked May 23 '19 10:05

Ankit Jain


2 Answers

The extension method AddStackExchangeRedisCache uses a ConnectionMultiplexer under the hood (see here, and here for the extension method itself).

@2: works in prod either way
@3: connection is established lazily on first use, the ConnectionMultiplexer instance is re-used (registered as DI singleton)
@4: yeah, see above resp. here, a SemaphoreSlim is used to ensure the connection is only created once

pros and cons: since both use the ConnectionMultiplexer, they are pretty similar.
You can pick between the advantages of using the implementation agnostic IDistributedCache vs. direct use of the multiplexer and the StackExchange.Redis API (which has more specific functions than the interface).

like image 52
enzi Avatar answered Oct 02 '22 15:10

enzi


With ConnectionMultiplexer, you have the full list of commands that you can execute on your Redis server. With DistributedCaching, you can only store/retrieve a byte array or a string, and you can not execute any other commands that Redis provides. So if you just want to use it as a cache store, DistributedCaching provides a good abstraction layer. However, even the simplest increment/decrement command for Redis will not be available, unless you use ConnectionMultiplexer.

like image 22
Ahmet Avatar answered Oct 02 '22 16:10

Ahmet