Redis Hello World with C# and .NET
Full source code available here.
It is very easy to use Redis with C#, and it is even easier when you don’t even need to install Redis on your computer - I used the docker image available here.
Follow the download instructions and run it using -
docker run -it --rm --name my-redis -p 6379:6379 redis
I added the StackExchange.Redis
package to my application.
Reading and writing with Redis is very simple -
1using StackExchange.Redis;
2using System;
3using System.Threading.Tasks;
4
5class Program
6{
7
8 static async Task Main()
9 {
10 var redis = connectionMultiplexer.GetDatabase();
11
12 Console.WriteLine("Writing to the cache...\n");
13 await redis.StringSetAsync("hello", "world");
14
15 Console.WriteLine("Reading from the cache...");
16 Console.WriteLine($"hello={await redis.StringGetAsync("hello")}\n");
17
18 Console.WriteLine("Clearing the cache...");
19 await redis.KeyDeleteAsync("hello");
20 }
21
22 static readonly ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(new ConfigurationOptions
23 {
24 EndPoints = { "localhost" }
25 });
26}
Full source code available here.