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

3

30

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.

Photoactinic answered 23/5, 2019 at 10:11 Comment(0)
M
29

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.

Maccarthy answered 4/6, 2019 at 1:39 Comment(1)
Thanks a lot for the response. I went ahead with the Distributed Cache because of the simplicity of the caching operations.Photoactinic
I
24

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).

Inextirpable answered 27/1, 2020 at 22:3 Comment(0)
P
2

Wrappers like IDistributedCache and StackExchangeRedis.Extensions do not include all the functions possible in the original library, In particular I required to delete All the keys in Redis Cache, which was not exposed in these wrappers.

Picked answered 24/5, 2022 at 5:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.