Spring Data Redis
环境搭建
Maven依赖
SpringBoot已经将Jedis依赖跟SpringDataRedis的依赖整合好了,直接导入spring-boot-starter-data-redis即可
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
application.yml配置
spring: redis: # Redis数据库索引(默认为0) database: 0 # Redis服务器地址 host: 192.168.253.132 # Redis服务器连接端口 port: 6379 # Redis服务器连接密码(默认为空) password: pool: # 连接池最大连接数(使用负值表示没有限制) max-active: 8 # 连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1 # 连接池中的最大空闲连接 max-idle: 8 # 连接池中的最小空闲连接 min-idle: 0 # 连接超时时间(毫秒) timeout: 0
使用Spring Data Redis
Spring Data Redis提供了Template操作Redis,分别是RedisTemplate跟StringRedisTemplate
SpringRedisTeplate是专门用来操作字符串的,key跟value都是String类型。
RedisTemplate的key是String类型,value是Object类型,可以用来操作Set、ZSet、HshMap等
RedisTemplate
如下定义了RedisTemplate对五种数据结构进行操作
redisTemplate.opsForValue();//操作字符串 redisTemplate.opsForHash();//操作hash redisTemplate.opsForList();//操作list redisTemplate.opsForSet();//操作set redisTemplate.opsForZSet();//操作有序set
解决RedisTemplate乱码问题
当使用RedisTemplate向redis中存值的时候会出现乱码,如下
要解决乱码的问题就必须在配置类中添加如下代码:
@Configuration public class RedisConfig { @Resource private RedisTemplate<String, Object> redisTemplate; @Bean public RedisTemplate<String, Object> stringSerializerRedisTemplate() { RedisSerializer<String> stringSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringSerializer); redisTemplate.setValueSerializer(stringSerializer); redisTemplate.setHashKeySerializer(stringSerializer); redisTemplate.setHashValueSerializer(stringSerializer); return redisTemplate; } }
opsForValue()
该方法返回一个对象对字符串进行操作
方法 |
说明 |
参数 |
示例 |
对应命令 |
void set(K key, V value); |
存字符串,如果键存在,覆盖 |
|
redisTemplate.opsForValue().set("name", "ericJin"); |
SET name ericJin |
void set(K key, V value, long timeout, TimeUnit unit); |
存字符串并设置时间 |
timeout:设置过期时间 unit:设置单位,秒、时、分什么的 |
redisTemplate.opsForValue().set("name", "test", 10, TimeUnit.SECONDS); |
SET name ericjin EX 10 |
void set(K key, V value, long offset); |
使用value值覆写指定key的值,从指定索引(offset)开始 |
offset:指定从哪里开始覆写 |
redisTemplate.opsForValue().set("name", " hello", 2); |
SETRANGE name 3 " hello" |
boolean setIfAbsent(K key, V value); |
如果键不存在则新增,存在则不改变已经有的值。 |
|
redisTemplate.opsForValue().setIfAbsent("name1", "test"); |
SETNX name1 test |
void multiSet(Map<? extends K, ? extends V> map); |
插入多个键值对 |
map:存放多个待存入的键值对 |
redisTemplate.opsForValue().multiSet(map); |
MSET name7 "ggg" name8 "bbbb" |
Boolean multiSetIfAbsent(Map<? extends K, ? extends V> m); |
如果对应的map集合名称不存在,则添加,如果存在则不做修改。 |
|
redisTemplate.opsForValue().multiSetIfAbsent(map); |
|
V get(Object key); |
获取键对应的值 |
|
Object name = redisTemplate.opsForValue().get("name"); |
GET name |
V getAndSet(K key, V value) |
设置字符串返回并旧值 |
|
Object oldVal = redisTemplate.opsForValue().getAndSet("name", "table"); |
GETSET name table1 |
multiGet(Collection<K> keys); |
一次性取出多个值 |
keys:要取出的键的集合 |
redisTemplate.opsForValue().multiGet(objects) |
MGET name name1 name2 |
Long increment(K key, long delta); |
将指定键对应的值加上delta,支持整数 |
|
redisTemplate.opsForValue().increment("num", 5); |
INCRBY num 4 |
Long increment(K key); |
给指定的键对应的值加一 |
|
redisTemplate.opsForValue().increment("num"); |
INCR num |
Double increment(K key, double delta); |
将指定键对应的值加上delta,支持浮点数 |
|
redisTemplate.opsForValue().increment("num", 12.3); |
|
Integer append(K key, String value); |
如果key已经存在并且是一个字符串,则该命令将该值追加到字符串的末尾。如果键不存在,则它被创建并设置为value,跟SET key value一样 |
|
redisTemplate.opsForValue().append("name", "hello"); |
APPEND name16 hhh |
String get(K key, long start, long end); |
截取指定位置的key对应的value字符串 |
|
String name = redisTemplate.opsForValue().get("name", 0, 5); |
|
Long size(K key); |
返回key所对应的value值得长度 |
|
Long name = redisTemplate.opsForValue().size("name"); |
STRLEN name |
Boolean setBit(K key, long offset, boolean value); |
对 key 所储存的字符串值,设置或清除指定偏移量上的位(bit) key键对应的值value对应的ascii码,在offset的位置(从左向右数)变为value |
|
template.opsForValue().set("bitTest","a"); // 'a' 的ASCII码是 97。转换为二进制是:01100001 // 'b' 的ASCII码是 98 转换为二进制是:01100010 // 'c' 的ASCII码是 99 转换为二进制是:01100011 //因为二进制只有0和1,在setbit中true为1,false为0,因此我要变为'b'的话第六位设置为1,第七位设置为0 template.opsForValue().setBit("bitTest",6, true); template.opsForValue().setBit("bitTest",7, false); System.out.println(template.opsForValue().get("bitTest")); |
SETBIT bitset 5 1 |
Boolean getBit(K key, long offset); |
将对应字符的ascii码值转换成二进制后,获取对应位置(offset)上的数为0还是1 |
|
redisTemplate.opsForValue().getBit("bitTest",7) |
GETBIT bitset 7 |
opsForList()
方法 |
说明 |
参数 |
示例 |
命令 |
List<V> range(K key, long start, long end); |
返回指定索引范围的值 |
|
redisTemplate.opsForList().range("list1", 0, 2) |
LRANGE list1 0 2
|
void set(K key, long index, V value); |
在列表中index的位置设置value值 |
|
redisTemplate.opsForList().set("list1", 2, "php"); |
LSET list1 2 hhhh |
Long leftPush(K key, V value); |
将所有指定的值插入存储在键的列表的头部。如果键不存在,则在执行推送操作之前将其创建为空列表。(从左边插入) |
|
redisTemplate.opsForList().leftPush("list1", "python"); |
LPUSH list1 python |
Long leftPushAll(K key, V... values); |
从列表的左边批量插入多个数据 |
|
redisTemplate.opsForList().leftPushAll("list1", "python", "java", "c++"); |
LPUSH list1 python java c++ |
Long leftPushAll(K key, Collection<V> values); |
把一个集合插入进列表 |
|
|
|
Long leftPushIfPresent(K key, V value); |
只有存在key对应的列表才能将这个value值插入到key所对应的列表中 |
|
|
|
Long leftPush(K key, V pivot, V value); |
把value值放到key对应列表中pivot值的左面,如果pivot值存在的话 |
|
redisTemplate.opsForList().leftPush("list1", "python", "java1"); |
|
Long rightPush(K key, V value); |
将所有指定的值插入存储在键的列表的头部。如果键不存在,则在执行推送操作之前将其创建为空列表。(从右边插入) |
|
redisTemplate.opsForList().rightPush("list1", "test"); |
RPUSH list1 jjjjjjj |
Long rightPushAll(K key, V... values); |
插入多个值 |
|
redisTemplate.opsForList().rightPushAll("list1", "gggg", "dnanfda", "nshfsdh"); |
RPUSH list1 kklk dshfjhd fdhfjdhfj |
Long rightPushAll(K key, Collection<V> values); |
将集合的值插入列表 |
|
|
|
Long rightPushIfPresent(K key, V value); |
只有存在key对应的列表才能将这个value值插入到key所对应的列表中 |
|
|
|
Long rightPush(K key, V pivot, V value); |
把value值放到key对应列表中pivot值的右面,如果pivot值存在的话 |
|
|
|
Long remove(K key, long count, Object value); |
从存储在键中的列表中删除value,其中value可能有多个,删除规则由count指定,如果count大于0,删除从头到尾遇到的第一个value;如果count小于0,删除从尾到头遇到的第一个value;如果count等于0,删除所有的value |
|
redisTemplate.opsForList().remove("list1", 1, "php"); |
|
V index(K key, long index); |
根据下标值获取列表内的元素 |
|
redisTemplate.opsForList().index("list1", 1) |
|
V leftPop(K key); |
弹出最左边的元素,弹出之后该值在列表中将不再存在 |
|
redisTemplate.opsForList().leftPop("list1") |
LPOP list1 |
V leftPop(K key, long timeout, TimeUnit unit); |
移出并获取列表的第一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。 |
|
redisTemplate.opsForList().leftPop("list2", 2, TimeUnit.SECONDS) |
BLPOP list2 5 |
V rightPop(K key); |
弹出最右边的元素,弹出之后该值在列表中将不再存在 |
|
redisTemplate.opsForList().rightPop("list1") |
RPOP list1 |
V rightPop(K key, long timeout, TimeUnit unit); |
移出并获取列表的最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。 |
|
|
BRPOP list2 5 |
V rightPopAndLeftPush(K sourceKey, K destinationKey); |
用于移除列表的最后一个元素,并将该元素添加到另一个列表并返回。 |
|
redisTemplate.opsForList().rightPopAndLeftPush("list1", "list2"); |
|
V rightPopAndLeftPush(K sourceKey, K destinationKey, long timeout, TimeUnit unit); |
用于移除列表的最后一个元素,并将该元素添加到另一个列表并返回,如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止。 |
|
|
|
opsForHash()
方法 |
说明 |
参数 |
示例 |
命令 |
Long delete(H key, Object... hashKeys); |
删除给定的哈希hashKeys |
|
redisTemplate.opsForHash().delete("hashset", "age"); |
HDEL hashset age |
Boolean hasKey(H key, Object hashKey); |
确定键是否存在 |
|
redisTemplate.opsForHash().hasKey("hashset", "name") |
HEXISTS hashset name |
HV get(H key, Object hashKey); |
获取散列中获取指定键对应的值 |
|
redisTemplate.opsForHash().get("hashset", "name") |
HGET hashset name |
List<HV> multiGet(H key, Collection<HK> hashKeys); |
从散列中获取多个键对应的值 |
|
redisTemplate.opsForHash().multiGet("hashset", Arrays.asList("name", "age")) |
HMGET hashset name age
|
Long increment(H key, HK hashKey, long delta); |
将散列中指定键对应的值自加delta(整数) |
|
redisTemplate.opsForHash().increment("hashset", "age", 5) |
|
Double increment(H key, HK hashKey, double delta); |
将散列中指定键对应的值自加delta(浮点数) |
|
|
|
Set<HK> keys(H key); |
获取某个散列下所有的key |
|
redisTemplate.opsForHash().keys("hashset") |
|
Long size(H key); |
获取指定散列的长度 |
|
redisTemplate.opsForHash().size("hashset") |
|
void putAll(H key, Map<? extends HK, ? extends HV> m); |
将多个键值对插入散列中 |
|
redisTemplate.opsForHash().putAll("hashset", map); |
HMSET hashset goodAt baskteball country china |
void put(H key, HK hashKey, HV value); |
设置一个键值对到散列 |
|
redisTemplate.opsForHash().put("hashset", "address", "changde Hunan Provience"); |
HSET hashset age 10 |
Boolean putIfAbsent(H key, HK hashKey, HV value); |
当且仅当散列中的键不存在时才设置 |
|
redisTemplate.opsForHash().putIfAbsent("hashset", "name1", "eric"); |
HSETNX hashset name eric |
List<HV> values(H key); |
获取整个散列存储的值 |
|
redisTemplate.opsForHash().values("hashset") |
|
Map<HK, HV> entries(H key); |
获取整个散列的所有键值对 |
|
redisTemplate.opsForHash().entries("hashset") |
|
Cursor<Map.Entry<HK, HV>> scan(H key, ScanOptions options); |
迭代散列中的键值对 |
|
Cursor<Map.Entry<Object, Object>> hashset = redisTemplate.opsForHash().scan("hashset", ScanOptions.NONE); while(hashset.hasNext()) { Map.Entry<Object, Object> next = hashset.next(); System.out.printf("%s = %s", next.getKey(), next.getValue()); } |
|
opsForSet()
集合中的元素无序且不能重复
方法 |
说明 |
参数 |
示例 |
命令 |
Long add(K key, V... values); |
无序集合中添加元素,返回添加个数 |
|
redisTemplate.opsForSet().add("set1", "hh", "xx", "yy", "hehe"); |
SADD set1 shahj dhsadh hfkdbf |
Long remove(K key, Object... values); |
移除集合中一个或多个成员 |
|
redisTemplate.opsForSet().remove("set1", "hh", "xx"); |
SREM set1 yy hh |
V pop(K key); |
移除并返回集合中的一个随机元素 |
|
redisTemplate.opsForSet().pop("set1"); |
SPOP set1 |
Boolean move(K key, V value, K destKey); |
将value从集合key移动到destKey |
|
redisTemplate.opsForSet().move("set2", "jj", "set1"); |
SMOVE set1 set2 name |
Long size(K key); |
计算集合的长度 |
|
redisTemplate.opsForSet().size("set1") |
SCARD set1 |
Boolean isMember(K key, Object o); |
判断 member 元素是否是集合 key 的成员 |
|
redisTemplate.opsForSet().isMember("set1", "kk") |
SISMEMBER set1 kk |
Set<V> intersect(K key, K otherKey); |
key对应的无序集合与otherKey对应的无序集合求交集 |
|
redisTemplate.opsForSet().intersect("set1", "set2") |
SINTER set1 set2 |
Set<V> intersect(K key, Collection<K> otherKeys); |
key对应的无序集合与多个otherKey对应的无序集合求交集 |
|
|
|
Long intersectAndStore(K key, K otherKey, K destKey); |
key无序集合与otherkey无序集合的交集存储到destKey无序集合中 |
|
redisTemplate.opsForSet().intersectAndStore("set1", "set2", "set3"); |
SINTERSTORE destKey set1 set2
注意,命令的目标集合在第一个 |
Long intersectAndStore(K key, Collection<K> otherKeys, K destKey); |
key对应的无序集合与多个otherKey对应的无序集合求交集存储到destKey无序集合中 |
|
|
|
Set<V> union(K key, K otherKey); |
key无序集合与otherKey无序集合的并集 |
|
redisTemplate.opsForSet().union("set1", "set2") |
SUNION set1 set2 set3 |
Set<V> union(K key, Collection<K> otherKeys); |
key无序集合与多个otherKey无序集合的并集 |
|
|
|
Long unionAndStore(K key, K otherKey, K destKey); |
key无序集合与otherkey无序集合的并集存储到destKey无序集合中 |
|
redisTemplate.opsForSet().unionAndStore("set1", "set2", "set5"); |
SUNIONSTORE destKey key1 key2 key3 注意:destKey在第一个 |
Long unionAndStore(K key, Collection<K> otherKeys, K destKey); |
key无序集合与多个otherkey无序集合的并集存储到destKey无序集合中 |
|
|
|
Set<V> difference(K key, K otherKey); |
key无序集合与otherKey无序集合的差集 |
|
redisTemplate.opsForSet().difference("set1", "set2") |
SDIFF set1 set2 set3 |
Set<V> difference(K key, Collection<K> otherKeys); |
key无序集合与多个otherKey无序集合的差集 |
|
|
|
Long differenceAndStore(K key, K otherKey, K destKey); |
key无序集合与otherkey无序集合的差集存储到destKey无序集合中 |
|
redisTemplate.opsForSet().differenceAndStore("set1", "set2", "set6"); |
SDIFFSTORE destkey key1 key2 key3 注意:destKey在第一个 |
Long differenceAndStore(K key, Collection<K> otherKeys, K destKey); |
key无序集合与多个otherkey无序集合的差集存储到destKey无序集合中 |
|
|
|
Set<V> members(K key); |
返回集合中的所有成员 |
|
redisTemplate.opsForSet().members("set1") |
SMEMBERS set1 |
V randomMember(K key); |
随机获取key无序集合中的一个元素 |
|
redisTemplate.opsForSet().randomMember("set1") |
SRANDMEMBER set1 |
Set<V> distinctRandomMembers(K key, long count); |
获取多个元素,count是获取的个数 |
|
redisTemplate.opsForSet().distinctRandomMembers("set1", 2) |
|
List<V> randomMembers(K key, long count); |
获取多个元素,count是获取的个数 |
|
|
SRANDMEMBER set1 2 |
Cursor<V> scan(K key, ScanOptions options); |
遍历集合 |
|
Cursor<Object> set1 = redisTemplate.opsForSet().scan("set1", ScanOptions.NONE); while(set1.hasNext()) { System.out.println(set1.next()); } |
|
opsForZSet()
有序集合,集合内元素不能重复
与而无序集合不同的是,有序集合里面的元素都会有一个分值,集合会根据这个分值来进行排序
方法 |
说明 |
参数 |
示例 |
命令 |
Boolean add(K key, V value, double score); |
新增一个有序集合,存在的话为false,不存在的话为true |
|
redisTemplate.opsForZSet().add("zset1", "hh", 1.0) |
ZADD zset1 2 xx |
Long add(K key, Set<TypedTuple<V>> tuples); |
新增一个有序集合 |
|
DefaultTypedTuple<Object> nn = new DefaultTypedTuple<>("nn", 3.0); DefaultTypedTuple<Object> nn1 = new DefaultTypedTuple<>("nn1", 4.0); DefaultTypedTuple<Object> nn2 = new DefaultTypedTuple<>("nn2", 5.0); HashSet<ZSetOperations.TypedTuple<Object>> objects = new HashSet<>(); objects.add(nn); objects.add(nn1); objects.add(nn2); redisTemplate.opsForZSet().add("zset1", objects); |
ZADD zset1 8 nj 9 nj1 |
Long remove(K key, Object... values); |
从有序集合中移除一个或者多个元素 |
|
redisTemplate.opsForZSet().remove("zset1", "nj"); |
ZREM zset1 nj nj1 |
Double incrementScore(K key, V value, double delta); |
增加元素的score值,并返回增加后的值 |
|
redisTemplate.opsForZSet().incrementScore("zset1", "nn1", 1.5); |
ZINCRBY zset1 10 nn1 |
Long rank(K key, Object o); |
返回有序集中指定成员的排名,从小到大 |
|
redisTemplate.opsForZSet().rank("zset1", "nn1") |
ZSCORE zset1 nn1 |
Long reverseRank(K key, Object o); |
返回有序集中指定成员的排名,从大到小 |
|
redisTemplate.opsForZSet().reverseRank("zset1", "nn1") |
ZREVRANK zset1 nn1 |
Set<V> range(K key, long start, long end); |
返回指定索引区间的值,从小到大 |
|
redisTemplate.opsForZSet().range("zset1", 0, 3) |
ZRANGE zset1 0 3 |
Set<V> reverseRange(K key, long start, long end); |
通过索引区间返回有序集合成指定区间内的成员,从大到小 |
|
|
ZREVRANGE zset1 0 3
|
Set<V> rangeByScore(K key, double min, double max); |
通过分数区间返回满足条件的成员,从小到大 |
|
redisTemplate.opsForZSet().rangeByScore("zset1", 1, 15.5) |
ZRANGEBYSCORE zset1 1 15.5 |
Set<V> reverseRangeByScore(K key, double min, double max); |
通过分数区间返回满足条件的成员,从大到小 |
|
|
ZREVRANGEBYSCORE zset1 1 15.5 |
Set<V> rangeByScore(K key, double min, double max, long offset, long count); |
通过分数返回有序集合指定区间内的成员,并在索引范围内,其中有序集成员按分数值递增(从小到大)顺序排列 |
|
template.opsForZSet().rangeByScore("zset1",0,5,1,2) |
|
Long count(K key, double min, double max); |
通过分数返回有序集合指定区间内的成员个数 |
|
template.opsForZSet().count("zset1",0,5) |
zcount key min max |
Long size(K key); |
获取有序集合的成员数 |
|
template.opsForZSet().size("zset1") |
zcard key |
Long zCard(K key); |
获取有序集合的成员数 |
|
template.opsForZSet().zCard("zset1") |
zcard key |
Double score(K key, Object o); |
获取指定成员的score值 |
|
template.opsForZSet().score("zset1","zset-1") |
zscore key member |
Long removeRange(K key, long start, long end); |
移除指定索引位置的成员,其中有序集成员按分数值递增(从小到大)顺序排列 |
|
template.opsForZSet().removeRange("zset2",1,2) |
ZREMRANGEBYRANK key start stop |
Long removeRangeByScore(K key, double min, double max); |
根据指定的score值得范围来移除成员 |
|
template.opsForZSet().removeRangeByScore("zset2",2,3) |
zremrangebyscore key min max |
Long unionAndStore(K key, K otherKey, K destKey); |
计算给定的一个有序集的并集,并存储在新的 destKey中,key相同的话会把score值相加 |
|
template.opsForZSet().unionAndStore("zzset1","zzset2","destZset11") |
ZUNIONSTORE destKey key1 key2 key3 注意:destKey在第一个 |
Long unionAndStore(K key, Collection<K> otherKeys, K destKey); |
计算给定的多个有序集的并集,并存储在新的 destKey中 |
|
|
|
Long intersectAndStore(K key, K otherKey, K destKey); |
计算给定的一个或多个有序集的交集并将结果集存储在新的有序集合 key 中 |
|
template.opsForZSet().intersectAndStore("zzset1","zzset2","destZset33") |
ZINTERSTORE destKey key1 key2 key3 |
Long intersectAndStore(K key, Collection<K> otherKeys, K destKey); |
计算给定的一个或多个有序集的交集并将结果集存储在新的有序集合 key 中 |
|
|
|
Cursor<TypedTuple<V>> scan(K key, ScanOptions options); |
遍历zset |
|
Cursor<ZSetOperations.TypedTuple<Object>> cursor = template.opsForZSet().scan("zzset1", ScanOptions.NONE); while (cursor.hasNext()){ ZSetOperations.TypedTuple<Object> item = cursor.next(); System.out.println(item.getValue() + ":" + item.getScore()); } |
|