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
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
- 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);
- }
The 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 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.