一、概述
Set和List类似,但是不同的就是Set中间没有重复值,可以理解成Set内部是一个value为null的HashMap,实际就是通过计算Hash的方式来进行快速排重的。
二、应用场景
从上面我们可以看出Set存储的是一组没有重复值的数据,那么我们就可以使用Set的这一特性来获取一组不需要重复值的数据。并且Redis给Set集合提供了求交集、并集和差集的操作。我们可以使用Set的这些特性来实现微博中的关注人的存储,求共同的关注人等操作。
三、Spring操作Redis的Set集合
(1)往Set中添加内容
二、应用场景
从上面我们可以看出Set存储的是一组没有重复值的数据,那么我们就可以使用Set的这一特性来获取一组不需要重复值的数据。并且Redis给Set集合提供了求交集、并集和差集的操作。我们可以使用Set的这些特性来实现微博中的关注人的存储,求共同的关注人等操作。
三、Spring操作Redis的Set集合
(1)往Set中添加内容
//添加数据
setOperations.add("name","liubei","zhangfei","zhangfei");
setOperations.add("name","zhangfei");
System.out.println(setOperations.members("name"));
输出结果:[zhangfei, liubei]
我们可以看出已经去除了集合中重复的“zhangfei”。
//获取并删除一个集合中的元素,输出结果为:[zhangfei]
setOperations.pop("name");
System.out.println(setOperations.members("name"));
//合并两个集合存入第三个集合
setOperations.add("name2","caocao","liubei");
setOperations.add("name3","guanyu");
setOperations.unionAndStore("name2","name3","NAME");
System.out.println(setOperations.members("NAME"));
//取两个集合的交集
System.out.println(setOperations.intersect("NAME","name3"));
查看SetOperations<K, V>接口我们可以看见很多操作Set集合的方法
package org.springframework.data.redis.core;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public interface SetOperations<K, V> {
//向一个集合中添加数据
Long add(K var1, V... var2);
//移除集合中的指定数据
Long remove(K var1, Object... var2);
//移除集合中的一个元素并返回
V pop(K var1);
Boolean move(K var1, V var2, K var3);
Long size(K var1);
//判断一个元素是否是集合中的某个成员
Boolean isMember(K var1, Object var2);
//获取两个集合的交集
Set<V> intersect(K var1, K var2);
Set<V> intersect(K var1, Collection<K> var2);
Long intersectAndStore(K var1, K var2, K var3);
Long intersectAndStore(K var1, Collection<K> var2, K var3);
//获取两个集合的并集
Set<V> union(K var1, K var2);
Set<V> union(K var1, Collection<K> var2);
Long unionAndStore(K var1, K var2, K var3);
Long unionAndStore(K var1, Collection<K> var2, K var3);
//获取两个集合的差集
Set<V> difference(K var1, K var2);
Set<V> difference(K var1, Collection<K> var2);
Long differenceAndStore(K var1, K var2, K var3);
Long differenceAndStore(K var1, Collection<K> var2, K var3);
//获取一个集合中的所有成员
Set<V> members(K var1);
V randomMember(K var1);
Set<V> distinctRandomMembers(K var1, long var2);
List<V> randomMembers(K var1, long var2);
Cursor<V> scan(K var1, ScanOptions var2);
RedisOperations<K, V> getOperations();
}
源码查看地址:点击打开链接