首先redis在.net环境中需要引用几个DLL,它们分别是
我们以控制台程序为例来简单看一下最普通的redis的用法
注释写的很详细,大家可以看一下:
static RedisClient Redis = new RedisClient("127.0.0.1", 6379);//redis服务IP和端口 static void Main(string[] args) { //将字符串列表添加到redis List<string> storeMembers = new List<string>() { "one", "two", "three" }; storeMembers.ForEach(x => Redis.AddItemToList("additemtolist", x)); //得到指定的key所对应的value集合 var members = Redis.GetAllItemsFromList("additemtolist"); members.ForEach(s => Console.WriteLine("<br/>additemtolist :" + s)); // 获取指定索引位置数据 var item = Redis.GetItemFromList("addarrangetolist", 2); Console.WriteLine(item); //移除数据 var list = Redis.Lists["addarrangetolist"]; list.Clear();//清空 list.Remove("two");//移除指定键值 // list.RemoveAt(2);//移除指定索引位置数据 //存储对象(JSON序列化方法)它比object序列化方法效率高 Redis.Set<UserInfo>("userinfo", new UserInfo() { UserName = "李四", Age = 45 }); UserInfo userinfo = Redis.Get<UserInfo>("userinfo"); Console.WriteLine("name=" + userinfo.UserName + "age=" + userinfo.Age); //存储值类型数据 Redis.Set<int>("my_age", 12);//或Redis.Set("my_age", 12); int age = Redis.Get<int>("my_age"); Console.WriteLine("age=" + age); //object序列化方式存储 var ser = new ObjectSerializer(); //位于namespace ServiceStack.Redis.Support; bool result = Redis.Set<byte[]>("userinfo2", ser.Serialize(new UserInfo() { UserName = "张三", Age = 12 })); UserInfo userinfo2 = ser.Deserialize(Redis.Get<byte[]>("userinfo2")) as UserInfo; Console.WriteLine("name=" + userinfo2.UserName + "age=" + userinfo2.Age); //也支持列表 List<UserInfo> userinfoList = new List<UserInfo> { new UserInfo{UserName="zzl",Age=1,Id=1}, new UserInfo{UserName="zhz",Age=3,Id=2}, }; Redis.Set<byte[]>("userinfolist_serialize", ser.Serialize(userinfoList)); List<UserInfo> userList = ser.Deserialize(Redis.Get<byte[]>("userinfolist_serialize")) as List<UserInfo>; userList.ForEach(i => { Console.WriteLine("name=" + i.UserName + "age=" + i.Age); }); }
这是最原始的redis操作,下一节我将对redis操作进行封装,使它具有更大的扩展性。