Redis example with Docker in C#

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]

  1. Install docker software from here: https://docs.docker.com/docker-for-windows/install/
  2. Switch to “Linux” containers
2
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.

1
3

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.

4

2. Enter name of your application and storage location of it.

5
Configure new project

3. Create Product class with below properties

6
Product.cs

4. Create Product service class. here, we have hard coded the products for this example only.

7
ProductService.cs

5. Install Redis and Newtonsoft.Json nuget packages in to console application

8
Redis nuget package
10
Newtonsoft.Json nuget package

6. Add RedisHelper class. This class help us in creating and connecting with Redis server. “localhost:6379” is connecting string.

9
RedisHelper.cs

7. Below method is responsible to save data into cache. We have stored serialized object into cache.

11

8. Lets read data back from cache.

12

9. Here is the full program.cs class.

13
14
Program.cs

10. Lets run the project.

15
Output

You can find this simple solution from github location: https://github.com/jayesh-tanna/docker-redis-example

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *