在Redis中,咱们能够将Set类型看做为没有排序的字符集合,和List类型同样,咱们也能够在该类型的数据值上执行添加、删除或判断某一元素是否存在等操做。须要说明的是,这些操做的时间复杂度为O(1),即常量时间内完成次操做。Set可包含的最大元素数量是4294967295。
和List类型不一样的是,Set集合中不容许出现重复的元素,这一点和C++标准库中的set容器是彻底相同的。换句话说,若是屡次添加相同元素,Set中将仅保留该元素的一份拷贝。和List类型相比,Set类型在功能上还存在着一个很是重要的特性,即在服务器端完成多个Sets之间的聚合计算操做,如unions、intersections和differences。因为这些操做均在服务端完成,所以效率极高,并且也节省了大量的网络IO开销。(参考:http://www.cnblogs.com/stephen-liu74/archive/2012/02/15/2352512.html)html
Redis作缓存Set可能到的的比较多(一家之言,欢迎拍砖)redis
打开redis服务器:缓存
打开redis客户端:服务器
这就是一个set集合!网络
至于redisset的命令小伙伴们能够参考(http://redisdoc.com)数据结构
下面分享redis在.net中的使用方法spa
, 1,得到集合.net
1 // 获取sortset表中setId中的全部keys,倒序获取 2 public List<string> GetAllItemsFromSortedSetDesc(string setId) 3 { 4 List<string> result = ExecuteCommand<List<string>>(client => 5 { 6 return client.GetAllItemsFromSortedSetDesc(setId); 7 }); 8 return result; 9 } 10 11 12 public List<string> GetAllItemsFromSortedSet(string setId) 13 { 14 List<string> result = ExecuteCommand<List<string>>(client => 15 { 16 return client.GetAllItemsFromSortedSet(setId); 17 }); 18 return result; 19 } 20 21 22 // 获取sortset表中setId中的全部keys,values 23 public IDictionary<string, double> GetAllWithScoresFromSortedSet(string setId) 24 { 25 IDictionary<string, double> result = ExecuteCommand<IDictionary<string, double>>(client => 26 { 27 return client.GetAllWithScoresFromSortedSet(setId); 28 //return client.GetFromHash<Dictionary<string, string>>(hashID); 29 }); 30 31 return result; 32 }
2,删除某个setcode
// 删除某个KEY的值,成功返回TRUE public bool RemoveKey(string key) { bool result = false; result = ExecuteCommand<bool>(client => { return client.Remove(key); }); return result; } // 删除Set数据中的某个为item的值 public bool RemoveItemFromSet(string setId, string item) { byte[] bvalue = System.Text.Encoding.UTF8.GetBytes(item); bool result = ExecuteCommand<bool>(client => { var rc = client as RedisClient; if (rc != null) { return rc.SRem(setId, bvalue) == 1; } return false; }); return result; }
3,搜索htm
//搜索key public List<string> SearchKeys(string pattern) { List<string> result = ExecuteCommand<List<string>>(client => { return client.SearchKeys(pattern); }); return result; }
4,增长某个元素到set
public bool AddItemToSet(string setId, string item) { byte[] bvalue = System.Text.Encoding.UTF8.GetBytes(item); bool result = ExecuteCommand<bool>(client => { var rc = client as RedisClient; if (rc != null) { return rc.SAdd(setId, bvalue) == 1; } return false; }); return result; }
这里只分享几个方法,其实还有不少关于set的操做方法。
利用Redis提供的Sets数据结构,能够存储一些集合性的数据,好比在微博应用中,能够将一个用户全部的关注人存在一个集合中,将其全部粉丝存在一个集合。Redis还为集合提供了求交集、并集、差集等操做,能够很是方便的实现如共同关注、共同喜爱、二度好友等功能,对上面的全部集合操做,你还可使用不一样的命令选择将结果返回给客户端仍是存集到一个新的集合中。