This project demonstrates the use of in-memory caching (IMemoryCache
) and distributed caching (IDistributedCache
) with Redis in an ASP.NET Core application. There are two HTTP GET methods:
- One retrieves data from IMemoryCache.
- The other retrieves data from IDistributedCache using Redis as the cache store.
- Install the latest version of the .NET Core SDK from the official website.
- This project uses Redis for
IDistributedCache
. You can run Redis locally using Docker.
To pull and run Redis using Docker, execute the following steps:
- Pull Redis image from Docker Hub.
- Run Redis in a detached mode, mapping it to the default port
6379
.
-
For
IMemoryCache
(built into ASP.NET Core):- No additional packages are required as
IMemoryCache
is part of theMicrosoft.Extensions.Caching.Memory
package, which is included with ASP.NET Core.
- No additional packages are required as
-
For
IDistributedCache
with Redis:- Install the
Microsoft.Extensions.Caching.StackExchangeRedis
package to use Redis withIDistributedCache
.
- Install the
Clone the repository to your local machine using your preferred git client.
If you haven't already set up Redis, run it locally using Docker. Make sure Redis is running on port 6379
.
Ensure that your Redis configuration matches your setup. By default, Redis is expected to run on localhost:6379
.
Use your development environment or the command line to build and run the application.
There are two HTTP GET endpoints available:
-
Retrieve data from
IMemoryCache
:- Endpoint:
/api/Cache/GetInMemoryCacheData
- This endpoint returns data cached in memory (server-side).
- Endpoint:
-
Retrieve data from
IDistributedCache
(Redis):- Endpoint:
/api/Cache/GetDistributedCacheData
- This endpoint returns data from the Redis-based distributed cache.
- Endpoint:
Make sure your appsettings.json
file has Redis configured correctly:
- This is an in-memory caching implementation. Data is cached in the memory of the running application and is available as long as the application is running.
IDistributedCache
is a distributed caching solution where cache data can be shared across multiple servers. In this project, Redis is used as the caching store. Redis ensures that the cache data is persisted outside of the application’s memory, making it suitable for distributed applications.
- Sliding Expiration and Absolute Expiration can be configured for both
IMemoryCache
andIDistributedCache
as demonstrated in the code. - You can configure expiration policies and customize cache behavior according to your needs.
- Microsoft.Extensions.Caching.Memory: For
IMemoryCache
, included in ASP.NET Core. - Microsoft.Extensions.Caching.StackExchangeRedis: For
IDistributedCache
with Redis.