StackExchange.Redis simple C# Example
Asked Answered
T

3

24

I am looking for a very simple starter C# application for using StackExchange.Redis I have search over the web and found StackExchange.Redis

But this doesn't seems like a quick startup example.

I have setup redis on windows using StackExchange.Redis exe

Can anyone help me locate a simple C# application connecting with redis server and setting and getting some keys.

Tripetalous answered 1/10, 2015 at 13:12 Comment(2)
Are you looking to use caching or state server?Emlin
Have you seen the readme?Tehuantepec
T
35

You can find C# examples in the readme file.

using StackExchange.Redis;
...

ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
// ^^^ store and re-use this!!!

IDatabase db = redis.GetDatabase();
string value = "abcdefg";
db.StringSet("mykey", value);
...
string value = db.StringGet("mykey");
Console.WriteLine(value); // writes: "abcdefg"
Tehuantepec answered 1/10, 2015 at 14:16 Comment(3)
I also recommend you the CachingFramework.Redis library that is built on top of SE.Redis and provides extra functionality like tagging mechanism, pluggable serialization and lot more.Tehuantepec
This is a bad example - the redis object is long-lived and example doesn't capture thatInjunction
@Abr you're right, so I've edited and added a comment to the code sampleTehuantepec
A
8

See the following code from their github sample:

 using (var muxer = ConnectionMultiplexer.Connect("localhost,resolvedns=1"))
        {
            muxer.PreserveAsyncOrder = preserveOrder;
            RedisKey key = "MBOA";
            var conn = muxer.GetDatabase();
            muxer.Wait(conn.PingAsync());

            Action<Task> nonTrivial = delegate
            {
                Thread.SpinWait(5);
            };
            var watch = Stopwatch.StartNew();
            for (int i = 0; i <= AsyncOpsQty; i++)
            {
                var t = conn.StringSetAsync(key, i);
                if (withContinuation) t.ContinueWith(nonTrivial);
            }
            int val = (int)muxer.Wait(conn.StringGetAsync(key));
            watch.Stop();

            Console.WriteLine("After {0}: {1}", AsyncOpsQty, val);
            Console.WriteLine("({3}, {4})\r\n{2}: Time for {0} ops: {1}ms; ops/s: {5}", AsyncOpsQty, watch.ElapsedMilliseconds, Me(),
                withContinuation ? "with continuation" : "no continuation", preserveOrder ? "preserve order" : "any order",
                AsyncOpsQty / watch.Elapsed.TotalSeconds);
        }
Adolf answered 2/10, 2015 at 5:7 Comment(6)
Your link is 404 now... what is AsyncOpsQty?Bloxberg
github.com/StackExchange/StackExchange.Redis/blob/master/tests/…Adolf
This is a bad example because the Connection Multiplexer object is LONG LIVED! It should not be used in this wayInjunction
Agreed. This is example was around 2015 when i have nearly first used it. Even the provided sample doesn't exists from which i have referred it .You are free to post a good example in the answer :)Adolf
You also forgot to increase minimum worker thread pool count.Feliks
@TimLovell-Smith this post is at the time of .net framework related implenetation. I faced minimum thread pool related problem only in .net core type of appliction which i handled there separatelyAdolf
S
3
  • //-- Install-Package StackExchange.Redis -Version 1.2.6
  • In this simple example: set new string key/value to redis with expiry time, get redis string value by key from redis:
  • Code:
    public string GetRedisValue()
    {
        var cachedKey = "key";
        string value;
    
        using (var redis = ConnectionMultiplexer.Connect("localhost:6379"))
        {
            IDatabase db = redis.GetDatabase();
    
            if (!db.KeyExists(cachedKey))
            {
                value = DateTime.Now.ToString();
                //set new value
                db.StringSet(cachedKey, value, TimeSpan.FromSeconds(18));
            }
            else
            {
                //get cached value
                value = db.StringGet(cachedKey);
            }
        }
    
        return value;
    }
    
Sterilant answered 18/8, 2021 at 1:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.