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 --name my-redis -p 6379:6379 redis 

I added the StackExchange.Redis package to my application.

Reading and writing with Redis is very simple -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using StackExchange.Redis;
using System;
using System.Threading.Tasks;

class Program
{

    static async Task Main()
    {
        var redis = connectionMultiplexer.GetDatabase();

        Console.WriteLine("Writing to the cache...\n");
        await redis.StringSetAsync("hello", "world");

        Console.WriteLine("Reading from the cache...");
        Console.WriteLine($"hello={await redis.StringGetAsync("hello")}\n");

        Console.WriteLine("Clearing the cache...");
        await redis.KeyDeleteAsync("hello");
    }

    static readonly ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(new ConfigurationOptions
    {
        EndPoints = { "localhost" }
    });
}

 
Full source code available here.

comments powered by Disqus

Related