Redis系列2- C#中使用Redis的樣本

來源:互聯網
上載者:User

標籤:set   服務   一個   color   list   預設值   csharp   合數   bsp   

上一篇Redis的系列已經講了Redis的下載、安裝,接下來這一篇,主要講使用Redis提供的 ServiceStack.Redis 這個開發庫在C#項目中作為快取服務使用的一個簡單樣本,廢話不多話,直接上代碼。



        private void TestRedis()        {            var Redis = new RedisClient("localhost"); //建立Redis執行個體(主機名稱根據項目的實際情況設定,可以使用設定檔的形式配置)            var records = new List<TestInfo>();            /*****操作泛型資料*******/            if (Redis.Exists("TestInfos") <= 0) //判斷某個緩衝是否存在            {                //添加泛型集合資料                Redis.Set("TestInfos", new List<TestInfo>()                {                    new TestInfo() { id = 1, name = "11" },                    new TestInfo() { id = 2, name = "22" },                    new TestInfo() { id = 3, name = "33" },                    new TestInfo() { id = 4, name = "44" }                });                Redis.Expire("TestInfos", 60); //設定為一分鐘到期            }            records = Redis.Get<List<TestInfo>>("TestInfos"); //擷取Redis的快取資料            //Redis.Remove("TestInfos"); //刪除一個緩衝            //records = Redis.Get<List<TestInfo>>("TestInfos"); //刪除後嘗試重新擷取,結果為null(Redis中擷取不存在的參考型別時返回null)            /*****操作泛型資料*******/            /*****鏈表操作*******/            var testRedisList = Redis.As<TestInfo>();            IRedisList<TestInfo> testData = testRedisList.Lists["testData"]; //指定一個鏈表            Redis.Expire("testData", 60);  //設定為一分鐘到期            testData.AddRange(records); //添加資料            testRedisList.Save(); //儲存鏈表資料            var testDataList = Redis.As<TestInfo>().Lists["testData"].ToList(); //擷取鏈表資料            /*****鏈表操作*******/            /*****操作int類型資料*******/            if (Redis.Exists("TestInt") <= 0)             {                Redis.Set("TestInt", 11); //儲存一個int類型的緩步資料            }            var recordStr = Redis.Get<int>("TestInt"); //擷取資料            Redis.Remove("TestInt"); //刪除一個緩衝            var redisIntVal = Redis.Get<int>("TestInt"); //刪除後嘗試重新擷取,結果為0(Redis中擷取不存在的實值型別時返回預設值)            /*****操作int類型資料*******/        }

  

 

Redis系列2- C#中使用Redis的樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.