Exploring Redis cache with Docker using asp.net core- Part 1

Recap

In my previous article, we have gone through the concept of Docker and Docker vs Container. In case if you haven’t read yet, I encourage you to read from here.

Prerequisites

  • Docker desktop installed on your local machine
  • Visual Studio/ Visual Studio Code

Intro

Redis cache is an in-memory data structure store and can be used as database, message broker and cache. It supports data structure such as hashes, sets, lists, strings, stream etc. It includes other features such as

  • Transactions
  • Pub/Sub
  • Keys with limited time to live
  • Automatic failover

Running a Redis container

Pull the latest Redis version from the Docker hub by running

docker pull redis

Here we are giving it a name(local-redis) and exposed the default redis port- 6379

docker run -d -p 6379:6379 --name local-redis redis

Check it’s running with

docker ps

And view the log output with

docker logs local-redis

Run the Redis CLI in container

We are going to start a new interactive session(-it) inside a running container, and use it to run redis-cli.

docker exec -it local-redis sh

And now we are attached to our redis container. Let’s run redis-cli

# redis-cli

Try out some basic commands

If we send a “ping”, should get “Pong” back

127.0.0.1:6379> ping
PONG

Try to add some more commands such as set a key, increment a counter

127.0.0.1:6379> set name Anika
OK
127.0.0.1:6379> get name
"Anika"
127.0.0.1:6379> incr counter
(integer) 1
127.0.0.1:6379> incr counter
(integer) 2
127.0.0.1:6379> get counter
"2"

And when we’re done exit out of redis-cli and sh

127.0.0.1:6379> exit
# exit

Coding

Now, Redis is successfully running in docker. So, let’s understand how Redis works from the code perspective.

I have created an asp.net core web-api project for this article. Add StackExchange.Redis nuget package to the project

Let’s begin with Startup class

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            IConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            services.AddScoped(x => redis.GetDatabase());
        }

Above is the code for connecting to the Redis.

Here in the controller, I’m retrieving the data from the cache using the key attribute

[HttpGet("{key}")]
        public async Task<string> GetAsync(string key)
        {
            return await _database.StringGetAsync(key);
        }

In both the http post methods, I’m using KeyValuePair<string,string>

[HttpPost]
        public async Task PostAsync([FromBody]KeyValuePair<string, string> keyValue)
        {
            await _database.StringSetAsync(keyValue.Key, keyValue.Value);
        }

Above method is quite straightforward, it is just adding the KeyValuePair to the Cache.

[HttpPost(template:"expiry")]
        public async Task SaveExpiry([FromBody] KeyValuePair<string, string> keyValue)
        {
     
            await _database.StringSetAsync(keyValue.Key, keyValue.Value, expiry: TimeSpan.FromSeconds(10));
        }

More or less code remains same for SaveExpiry method except adding the expiry parameter to the StringSetAsync. I have set the time span of 10 seconds for the expiry parameter.

Note: I don’t recommend using expiry in the http post verb. Instead, you can implement it in WorkerService(i.e. BackGroundService). I’ll be posting an article on Azure Web jobs using the same example.

Finally, we have managed to put all the code changes in place. Run the application and verify the results.

It seems everything is working as expected.

In the part-2 series of the article, I’ll be concentrating on running the current application in docker and how the communication happens between containers(Redis and our application container).

I hope you like the article. In case if you find the article interesting then kindly like and share it.

One thought on “Exploring Redis cache with Docker using asp.net core- Part 1

  1. Pingback: Exploring Redis cache with Docker using asp.net core- Part 2 – Articles on latest .net technology

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s