课件.Redis简单的c#示例

本文关键字:示例 简单 Redis 课件 | 更新日期: 2023-09-27 18:15:24

我正在寻找一个非常简单的初学者c#应用程序使用StackExchange。复述,我在网上搜索,发现StackExchange。复述,

但是这看起来不像是一个快速启动的例子。

我已经设置redis在windows上使用课件。复述,exe

谁能帮我找到一个简单的c#应用程序连接到redis服务器和设置和获得一些键

课件.Redis简单的c#示例

您可以在自述文件中找到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示例中查看以下代码:

 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);
        }
  • //——Install-Package StackExchange。Redis -Version 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;
    }