寫在前面
最近公司搞了一個活動,用到了redis的隊列,就研究了下redis的相關內容。也順手做了個demo。
C#之使用Redis
可以通過Nuget安裝Reidis的相關程序集。安裝之后發現會引入以下幾個dll
一些list,隊列和hashtable的操作。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NServiceKit.Redis; using Newtonsoft.Json; namespace RedisDemo { class Program { static void Main(string[] args) { //創建redis工廠 RedisClientFactory factory = RedisClientFactory.Instance; //通過工廠創建redisclient對象 RedisClient client = factory.CreateRedisClient("192.168.1.37", 6379); //在list中添加鍵值對 client.AddItemToList("test_listId", "wolfy"); //通過鍵和索引取值 string value = client.GetItemFromList("test_listId", 0); //隊列 for (int i = 0; i < 10; i++) { client.EnqueueItemOnList("queue_test", "test" + i.ToString()); } while (client.GetListCount("queue_test") > 0) { Console.WriteLine(client.DequeueItemFromList("queue_test")); } //hashtable for (int i = 0; i < 10; i++) { client.SetEntryInHash("hashtable_test", "test" + i.ToString(), JsonConvert.SerializeObject(new { id = i + 1, name = "wolfy" + i.ToString() })); } //獲取hashtable中的值 List<string> lst = client.GetHashValues("hashtable_test"); foreach (var item in lst) { Console.WriteLine(item); } Console.Read(); } } }
測試
總結
關於redis的文章網上有很多,這里由於工作需要,先着手弄了個demo,先跑起來,然后再深入的研究。