首先,簡述一下什麼是Redis。redis
Redis是一個開源、支持網絡、基於內存、鍵值對存儲數據庫,使用ANSI C編寫。從2013年5月開始,Redis的開發由Pivotal贊助。在這以前,其開發由VMware贊助。根據月度排行網站DB-Engines.com的數據顯示,Redis是最流行的鍵值對存儲數據庫。數據庫
更詳盡的內容參見:網絡
public static void Main(string[] args) { var Redis = new RedisClient("127.0.0.1", 6379);//redis服務IP和端口 #region insert var storeMembers = new List<string> { "aaa", "bbb", "ccc" }; storeMembers.ForEach(x => Redis.AddItemToList("additemtolist", x)); //注:也可直接使用AddRangeToList方法將一組數據裝入如: Redis.AddRangeToList("additemtolist", storeMembers); #endregion #region get var members = Redis.GetAllItemsFromList("additemtolist"); members.ForEach(s => Console.WriteLine("additemtolist :" + s)); Console.WriteLine(Redis.GetItemFromList("additemtolist", 2)); #endregion #region delete var list = Redis.Lists["additemtolist"]; list.Clear();//清空 list.Remove("two");//移除指定鍵值 list.RemoveAt(2);//移除指定索引位置數據 #endregion #region object Redis.Set("userinfo", new UserInfo() { UserName = "張三", Age = 11 }); UserInfo userinfo = Redis.Get<UserInfo>("userinfo"); Console.WriteLine(userinfo.UserName); Redis.Set<int>("my_age", 12);//或Redis.Set("my_age", 12); Console.WriteLine(Redis.Get<int>("my_age")); #endregion var ser = new ObjectSerializer(); //位於namespace ServiceStack.Redis.Support; #region 序列化 bool result = Redis.Set<byte[]>("userinfo", ser.Serialize(new UserInfo() { UserName = "龍一", Age = 12 })); UserInfo userinfo = ser.Deserialize(Redis.Get<byte[]>("userinfo")) as UserInfo; Console.WriteLine(userinfo.UserName); #endregion //也支持列表 Redis.Set<byte[]>("userinfolist_serialize", ser.Serialize(userinfoList)); #region 負載均衡 PooledRedisClientManager prcm = CreateManager(new string[] { "10.0.4.210:6379" }, new string[] { "10.0.4.210:6379" }); List<UserInfo> userinfoList = new List<UserInfo>(); userinfoList.Add(new UserInfo() { UserName = "pool_daizhj", Age = 1 }); userinfoList.Add(new UserInfo() { UserName = "pool_daizhj1", Age = 2 }); // 從池中獲取一個連接: using (IRedisClient Redis2 = prcm.GetClient()) { Redis2.Set("userinfolist", userinfoList); List<UserInfo> userList = Redis2.Get<List<UserInfo>>("userinfolist"); } #endregion Console.ReadLine(); } public static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts) { //支持讀寫分離,均衡負載 return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 5,//「寫」連接池連接數 MaxReadPoolSize = 5,//「寫」連接池連接數 AutoStart = true, }); }