Step1:使用NuGet工具安装Redis C# API,这里有多个API我们可以使用其中一个:
这样在代码中使用Redis需要使用到的Dll就自动引用进来啦:
Step2:
也就是写代码了:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using ServiceStack.Redis; 7 8 namespace MvcDemo.Controllers 9 { 10 public class RedisController : Controller 11 { 12 // 13 // GET: /Redis/ 14 15 public ActionResult Index() 16 { 17 //链接redis服务器: ip+端口号 18 var client = new RedisClient("127.0.0.1", 6379); 19 bool isConnectSuccess= client.IsSocketConnected(); 20 21 //redis支持的 五中数据类型 字符串、Hash、Set、 22 23 #region 字符串 (常用作缓存) 24 client.Set("name","同程网"); 25 client.Set<string>("test", "longsi"); 26 string name = client.Get<string>("name"); 27 string test = client.Get<string>("test"); 28 ViewBag.name = name; 29 ViewBag.test = test; 30 #endregion 31 32 #region Hash 33 34 client.SetEntryInHash("memberInfo", "6631", "lxf"); 35 client.SetEntryInHash("memberInfo", "5227", "zjj"); 36 int length = (int)client.GetHashCount("memberInfo"); 37 Dictionary<string, string> dic = new Dictionary<string, string>(); 38 for (int i = 0; i < length; i++) 39 { 40 dic.Add(client.GetHashKeys("memberInfo")[i], client.GetHashValues("memberInfo")[i]); 41 } 42 ViewData["persons"] = dic; 43 #endregion 44 45 #region List (常用作并发处理中队任务队列) 46 47 //入队操作 48 client.EnqueueItemOnList("listKey", "李彦宏"); 49 client.EnqueueItemOnList("listKey", "李嘉诚"); 50 client.EnqueueItemOnList("listKey", "李小飞"); 51 52 List<string> myList = new List<string>(); 53 54 //出队操作 55 string strName1 = client.DequeueItemFromList("listKey"); 56 string strName2 = client.DequeueItemFromList("listKey"); 57 string strName3 = client.DequeueItemFromList("listKey"); 58 myList.Add(strName1); 59 myList.Add(strName2); 60 myList.Add(strName3); 61 62 //为什么下面这段代码会报错 ?? 求解 63 //while (!string.IsNullOrEmpty(strName)) 64 //{ 65 // myList.Add(strName); 66 // name= client.DequeueItemFromList("listKey"); 67 //} 68 69 ViewBag.MyList = myList; 70 71 #endregion 72 73 #region Redis中的队列也可当做栈来使用 74 75 //入栈操作 76 client.PushItemToList("stackKey","1"); 77 client.PushItemToList("stackKey", "2"); 78 client.PushItemToList("stackKey", "3"); 79 80 //出战操作 81 List<string> stack = new List<string>(); 82 string num = client.PopItemFromList("stackKey"); 83 while(!string.IsNullOrEmpty(num)) 84 { 85 stack .Add(num); 86 num = client.PopItemFromList("stackKey"); 87 } 88 89 ViewBag.Stack = stack; 90 91 #endregion 92 93 // Set和sorted Set不常用就不写了 94 95 return View(); 96 } 97 98 } 99 }
时间: 2024-11-01 13:53:21