Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. Lets install redis server in docker. Beauty of docker is that without installation of actual software, you can install it in docker and can access those application. Lets create a simple example and divide it in two parts.
First part: Installation of redis in windows OS on docker with Linux containers. Second part: To access redis from C# console application. We will store serialized object in redis and will retrieve stored value and display it on console.
[Part 1 – Installation of Redis in docker]
- Install docker software from here: https://docs.docker.com/docker-for-windows/install/
- Switch to “Linux” containers
3. Type this command in command line: docker run -p 6379:6379 redis
It will pull redis image from docker hub if it is not exist locally and it will install it. To connect redis with any application, we need to configure docker system’s port and its internal port. So here We’ve kept both ports same.
After above installation, Redis is accessible from localhost on port 6379.
[Part 2 – Access installed Redis from c# console application]
Lets create stand alone console application. It will store serialized products in to cache and then we will read data back from cache.
1. Select console app from VS template.
2. Enter name of your application and storage location of it.
3. Create Product class with below properties
4. Create Product service class. here, we have hard coded the products for this example only.
5. Install Redis and Newtonsoft.Json nuget packages in to console application
6. Add RedisHelper class. This class help us in creating and connecting with Redis server. “localhost:6379” is connecting string.
7. Below method is responsible to save data into cache. We have stored serialized object into cache.
8. Lets read data back from cache.
9. Here is the full program.cs class.
10. Lets run the project.
You can find this simple solution from github location: https://github.com/jayesh-tanna/docker-redis-example
Happy coding!