StackExchange.Redis 简单的 C# 示例

StackExchange.Redis simple C# Example

我正在寻找一个非常简单的入门 C# 应用程序来使用 StackExchange.Redis 我在网上搜索并找到 StackExchange.Redis

但这似乎不是一个快速启动示例。

我在 windows 上使用 StackExchange.Redis exe

任何人都可以帮我找到一个连接 Redis 服务器并设置和获取一些密钥的简单 C# 应用程序。

您可以在 readme 文件中找到 C# 示例。

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"

从他们的 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);
        }
  • //-- 安装包 StackExchange.Redis - 版本 1.2.6
  • 在这个简单的例子中:将新字符串key/value设置为redis并设置过期时间,通过key从redis中获取redis字符串值:
  • 代码:
    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;
    }