Exploring Redis Cache With Docker Using ASP.NET Core - Part One

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 it 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 structures 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 exposing 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", we should get  a"Pong" back
 
127.0.0.1:6379> ping PONG
 
Try to add some more commands such as set a key, increment and  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
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     services.AddControllers();  
  3.     IConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");  
  4.     services.AddScoped(x => redis.GetDatabase());  
  5. }  
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
  1. [HttpGet("{key}")]  
  2. public async Task < string > GetAsync(string key) {  
  3.     return await _database.StringGetAsync(key);  
  4. }  
In both the http post methods, I'm using KeyValuePair<string,string>
  1. [HttpPost]  
  2. public async Task PostAsync([FromBody] KeyValuePair < stringstring > keyValue) {  
  3.     await _database.StringSetAsync(keyValue.Key, keyValue.Value);  
  4. }   
The above method is quite straightforward, it is just adding the KeyValuePair to the Cache.
  1. [HttpPost(template: "expiry")]  
  2. public async Task SaveExpiry([FromBody] KeyValuePair < stringstring > keyValue) {  
  3.     await _database.StringSetAsync(keyValue.Key, keyValue.Value, expiry: TimeSpan.FromSeconds(10));  
  4. }   
More or less code remains the 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.
 
Exploring Redis Cache With Docker Using ASP.NET Core
 
Exploring Redis Cache With Docker Using ASP.NET Core
 
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 you find the article interesting then kindly like and share it.


Similar Articles