Redis缓存之Set使用

时间:2023-03-09 07:32:44
Redis缓存之Set使用

在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

Redis做缓存Set可能到的的比较多(一家之言,欢迎拍砖)

打开redis服务器:

Redis缓存之Set使用

打开redis客户端:

Redis缓存之Set使用

这就是一个set集合!

至于redisset的命令小伙伴们可以参考(http://redisdoc.com

下面分享redis在.net中的使用方法

,     1,获得集合

   // 获取sortset表中setId中的所有keys,倒序获取
public List<string> GetAllItemsFromSortedSetDesc(string setId)
{
List<string> result = ExecuteCommand<List<string>>(client =>
{
return client.GetAllItemsFromSortedSetDesc(setId);
});
return result;
} public List<string> GetAllItemsFromSortedSet(string setId)
{
List<string> result = ExecuteCommand<List<string>>(client =>
{
return client.GetAllItemsFromSortedSet(setId);
});
return result;
} // 获取sortset表中setId中的所有keys,values
public IDictionary<string, double> GetAllWithScoresFromSortedSet(string setId)
{
IDictionary<string, double> result = ExecuteCommand<IDictionary<string, double>>(client =>
{
return client.GetAllWithScoresFromSortedSet(setId);
//return client.GetFromHash<Dictionary<string, string>>(hashID);
}); return result;
}

2,删除某个set

        // 删除某个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,搜索

         //搜索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还为集合提供了求交集、并集、差集等操作,可以非常方便的实现如共同关注、共同喜好、二度好友等功能,对上面的所有集合操作,你还可以使用不同的命令选择将结果返回给客户端还是存集到一个新的集合中。