標籤: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的樣本