Redis Cache with .Net Core Console Application

Arkaprava Sinha
3 min readMar 21, 2021

Hello everyone, today we are going to learn how to work with Redis Cache in .Net Core Console Application

About Redis:

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. Redis provides data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes, and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

Things Required:

  1. Docker Desktop for Creating a Redis Instance. if you don’t have please install the same. For installation please follow this doc, https://docs.docker.com/docker-for-windows/install/
  2. VS2019

Nuget Packages Used:

<PackageReference Include="Newtonsoft.Json" Version="12.0.3" /><PackageReference Include="Polly" Version="7.2.1" /><PackageReference Include="StackExchange.Redis" Version="2.2.4" />

Steps:

  1. First we will create a redis instance in our local systems, to do that open Command Prompt.
  2. Run “docker pull redis”. It will pull the latest redis image from container image repositiry.

3. Now create a Redis Container and assign ports , Redis run from 6379 port so assign the inner container port to 6379 so that we will be able to communicate with Redis Instance.

docker run --name <instance-name> -p  5001:6379 -d redis

4. After this command executed successfully, you can check the status of container by running “docker ps -a”.

docker ps -a

5. To Check if Redis is up or not follow below steps,

a. Run “docker exec -it <instance-name> sh”, to run shell in the container

b. Then type “redis-cli” and press enter

c. Now you are in redis cli, run “Ping”, if it returns pong, means server is up and listening.

6. So now our Redis server has been deployed, now Open VS2019

7. Create a new .Net Core Console App Project.

8. Copy and paste below code in Program.cs, also please install all the required nuget packages mentioned above.

9. Now run the application your console will look like below,

Ouput

10. Now if you go and see in our redis instance, you will find these new keys as well.

You can also monitor your redis instance from Docker desktop, Open your docker desktop, under containers you will find your instance running.

If you click on your instance, you will find your instance details as well ,

Stats
Inspect
logs

Thanks for reading my blog, if you like the content please follow me for similar kind of contents. Next we will learn how to use redis in Web Applications and use of Azure Redis Cache.

--

--

Arkaprava Sinha

Senior Software Engineer@Walmart , Cloud, IoT and DevOps Enthusiast