ServiceStack.Redis常用操作 - 事務、併發鎖

一、事務

  使用IRedisClient執行事務示例:

複製代碼
    using (IRedisClient RClient = prcm.GetClient())
    {
        RClient.Add("key",1);
        using (IRedisTransaction IRT = RClient.CreateTransaction())
        {
            IRT.QueueCommand(r => r.Set("key", 20));
            IRT.QueueCommand(r => r.Increment("key",1)); 

            IRT.Commit(); // 提交事務
        }
        Response.Write(RClient.Get<string>("key"));
    }
複製代碼

 

二、併發鎖

  使用IRedisClient申請鎖示例:

複製代碼
    using (IRedisClient RClient = prcm.GetClient())
    {
        RClient.Add("mykey",1);
        // 支持IRedisTypedClient和IRedisClient
        using (RClient.AcquireLock("testlock")) 
        {
            Response.Write("申請併發鎖<br/>");
            var counter = RClient.Get<int>("mykey");

            Thread.Sleep(100);

            RClient.Set("mykey", counter + 1);
            Response.Write(RClient.Get<int>("mykey"));
        }
    }
複製代碼

 

發佈了46 篇原創文章 · 獲贊 9 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章