redis
电脑版发表于:2021/5/14 18:11
前言
Redis支持五种数据类型:String(字符串),hash(哈希),list(列表),set(集合),zset(有序集合)
启动redis缓存
redis字符串的存取
使用redis时需要先将redis启动
//实例化redis,using释放资源 //如果连接本地的redis并且端口是6379的话可以不指定ip与端口默认就这样 //直接实例化就行 using (RedisClient redisClient = new RedisClient()){ //存值 redisClient.Set<string>("name",value); //通过键取值 string city = redisclient.Get<string>("name"); };
redis数组的存取
using (RedisClient redisClient = new RedisClient()){ //往数组里添加数据 redisclient.AddItemToList("name", "张三"); redisclient.AddItemToList("name", "李四"); redisclient.AddItemToList("name", "王五"); //添加在数组开头 redisclient.PrependItemToList("test_users","李清照") //获取数组中的数据(根据下标) string val = redisclient.GetItemFromList("name", 1); //更新数组中的数据(根据下标) redisclient.SetItemInList("name", 1, "赵六"); //删除数组中的元素(返回受影响行数) long count = redisclient.RemoveItemFromList("name", "赵六"); //循环遍历数组中的数据 List<string> namelist= redisclient.GetAllItemsFromList("name"); foreach (string item in namelist) { Console.WriteLine(item); } //获取数组的元素的个数 long namelistcount = redisclient.GetListCount("name"); //遍历数组的元素的范围(网页分页数据) List<string> namelist= redisclient.GetRangeFromList("name", 0, 5); foreach (stringitem in namelist) { Console.WriteLine(item); } }
redis哈希的存取
using (RedisClient redisClient = new RedisClient()){ //添加/修改(哈希数组名称,Key,Value) redisClient .SetEntryInHash("userhash", "u1", "李白"); redisClient .SetEntryInHash("userhash", "u2", "韩信"); redisClient .SetEntryInHash("userhash", "u3", "赵云"); //获取(现在是value = 韩信)根据哈希数组名称+Key,获取value string value = redisClient .GetValueFromHash("userhash", "u2"); //删除(删除韩信) redisClient .RemoveEntryFromHash("userhash", "u2"); //遍历(返回值是键值对) Dictionary<string, string> kvalue = redisClient .GetAllEntriesFromHash("userhash"); foreach (var item in kvalue) { Console.WriteLine(item.Key + ":" + item.Value); } //输出所有的key List<string> keys = redisClient.GetHashKeys("userhash"); foreach (string item in keys) { Console.WriteLine(item); } //删除所有 foreach (string key in keys) { redisClient.RemoveEntryFromHash("userhash", key); } //输出所有的value List<string> values = redisClient .GetHashValues("userhash"); foreach (string item in values) { Console.WriteLine(item); } }