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
AddStackExchangeRedisCache - This happens in Startup.cs. Doubts in above approach:
Does this work in Prod environment?
When and how the connection is initialized?
Is it thread safe way to create the connection?
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:
I tried both approaches in my local machine both are working fine. But I could not find Pros and Cons of above approach.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With