Spring encapsulates RedisTemplate to operate Redis, which supports all Redis native APIs. Operation methods for 5 data structures are defined in RedisTemplate.
opsForValue(): Operation string.
opsForList(): Operation list.
opsForHash(): Operate hash.
opsForSet(): Operation set.
opsForZSet(): Operate an ordered set.
Let’s understand and apply these methods through examples. It is important to note that if run multiple times, failure to clear the data may result in repeated data operations, so be sure to clear the data after running the above method.
(1) Use Maven to add dependency files
In the pom.xml configuration information file, add Redis dependency:
My SpringBoot version:
org.springframework.boot spring-boot-starter-parent 2.3.4.RELEASE
Add Redis dependency:
org.springframework.boot spring-boot-starter-data-redis 2.3.3.RELEASE
(2) Redis configuration
Configure Redis information in the application.yml configuration file:
#Spring配置 spring: #缓存管理器 cache: type: redis #Redis配置 redis: database: 0 #Redis数据库索引(默认为0) host: 127.0.0.1 #Redis服务器地址 port: 6379 #Redis服务器连接端口 password: #Redis服务器连接密码(默认为空) jedis: pool: max-active: 8 #连接池最大连接数(使用负值表示没有限制) max-wait: -1s #连接池最大阻塞等待时间(使用负值表示没有限制) max-idle: 8 #连接池中的最大空闲连接 min-idle: 0 #连接池中的最小空闲连接 lettuce: shutdown-timeout: 100ms #关闭超时时间,默认值100ms
(3) Redis configuration class (config layer)
Create the com.pjb.config package, create the RedisConfig class (Redis configuration class), and inherit the CachingConfigurerSupport class.
package com.pjb.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import java.lang.reflect.Method; /** * Redis配置类 * @author pan_junbiao **/ @Configuration public class RedisConfig extends CachingConfigurerSupport { /** * 缓存对象集合中,缓存是以key-value形式保存的, * 当不指定缓存的key时,SpringBoot会使用keyGenerator生成Key。 */ @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); //类名+方法名 sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } /** * 缓存管理器 */ @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisConnectionFactory connectionFactory) { RedisCacheManager cacheManager = RedisCacheManager.create(connectionFactory); //设置缓存过期时间 return cacheManager; } /** * 实例化RedisTemplate对象 */ @Bean public RedisTemplateredisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
String (String) is the most basic data type of Redis. Each key (Key) corresponds to a corresponding value (Value) in String, that is, there are Key-Value key-value pairs. String is binary safe and can store any data (such as images or serialized objects). The maximum value can store 512MB of data. Generally used for caching some complex counting functions. RedisTemplate provides the following methods to operate on String.
For specific usage, see the following code:
/** * Redis操作字符串(String) * @author pan_junbiao **/ @SpringBootTest public class StringTest { @Autowired private RedisTemplate redisTemplate; @Test public void string1() { redisTemplate.opsForValue().set("userName","pan_junbiao的博客"); redisTemplate.opsForValue().set("blogUrl","https://blog.csdn.net/pan_junbiao"); redisTemplate.opsForValue().set("blogRemark","您好,欢迎访问 pan_junbiao的博客"); System.out.println("用户名称:" + redisTemplate.opsForValue().get("userName")); System.out.println("博客地址:" + redisTemplate.opsForValue().get("blogUrl")); System.out.println("博客信息:" + redisTemplate.opsForValue().get("blogRemark")); } }
Execution result:
The following code setting is invalid for 3s. The query will have results within 3s, and the query will return null after 3s. See the following code for specific usage:
@Autowired private RedisTemplate redisTemplate; @Test public void string2() { //设置的是3s失效,3s之内查询有结果,3s之后返回null redisTemplate.opsForValue().set("blogRemark","您好,欢迎访问 pan_junbiao的博客",3, TimeUnit.SECONDS); try { Object s1 = redisTemplate.opsForValue().get("blogRemark"); System.out.println("博客信息:" + s1); Thread.currentThread().sleep(2000); Object s2 = redisTemplate.opsForValue().get("blogRemark"); System.out.println("博客信息:" + s2); Thread.currentThread().sleep(5000); Object s3 = redisTemplate.opsForValue().get("blogRemark"); System.out.println("博客信息:" + s3); } catch (InterruptedException ie) { ie.printStackTrace(); } }
Execution results:
##1.3 V getAndSet(K key, V value) Sets the key's string and returns its old value. See the following code for specific usage:@Autowired private RedisTemplate redisTemplate; @Test public void string3() { //设置键的字符串并返回其旧值 redisTemplate.opsForValue().set("blogRemark","pan_junbiao的博客"); Object oldVaule = redisTemplate.opsForValue().getAndSet("blogRemark","您好,欢迎访问 pan_junbiao的博客"); Object newVaule = redisTemplate.opsForValue().get("blogRemark"); System.out.println("旧值:" + oldVaule); System.out.println("新值:" + newVaule); }
Execution result:
##1.4 Integer append(K key, V value)
@Autowired private RedisTemplate redisTemplate; @Test public void string4() { //设置value的序列化规则,否则会报错 redisTemplate.setValueSerializer(new StringRedisSerializer()); redisTemplate.opsForValue().append("blogRemark","您好,欢迎访问 "); System.out.println(redisTemplate.opsForValue().get("blogRemark")); redisTemplate.opsForValue().append("blogRemark","pan_junbiao的博客"); System.out.println(redisTemplate.opsForValue().get("blogRemark")); }
##Note:
must be here Pay attention to the deserialization configuration, otherwise an error will be reported.Returns the length of the value corresponding to the key, see the following code:1.5 Long size(K key)
@Autowired private RedisTemplate redisTemplate; @Test public void string5() { redisTemplate.opsForValue().set("userName","pan_junbiao的博客"); System.out.println("Value值:" + redisTemplate.opsForValue().get("userName")); System.out.println("Value值的长度:" + redisTemplate.opsForValue().size("userName")); }
Execution result:
2. List (List)
Redis list is a simple list of strings, sorted in insertion order. An element can be added to the head (left) or tail (right) of the list. Using list data results, you can perform simple message queue functions. Irange command can also be used to implement high-performance pagination based on Redis. 2.1 Long leftPushAll(K key, V... values); Long rightPushAll(K key, V... values) leftPushAll method: Indicates inserting an array into the list. rightPushAll method: means adding elements in batches to the rightmost part of the list. See the following code for specific usage:/** * Redis操作列表(List) * @author pan_junbiao **/ @SpringBootTest public class ListTest { @Autowired private RedisTemplate redisTemplate; @Test public void list1() { String[] user1 = new String[]{"1","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"}; String[] user2 = new String[]{"2","pan_junbiao的博客","https://blog.csdn.net/pan_junbiao"}; String[] user3 = new String[]{"3","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"}; redisTemplate.opsForList().rightPushAll("user1",user1); redisTemplate.opsForList().rightPushAll("user2",user2); redisTemplate.opsForList().rightPushAll("user3",user3); System.out.println(redisTemplate.opsForList().range("user1",0,-1)); System.out.println(redisTemplate.opsForList().range("user2",0,-1)); System.out.println(redisTemplate.opsForList().range("user3",0,-1)); } }
Execution result:
##2.2 Long leftPush(K key, V value); Long rightPush (K key, V value)
leftPush method: Inserts all specified values at the head of the key list. Before performing the push operation, if the key does not exist, an empty list is created and inserted to the left.
@Autowired private RedisTemplate redisTemplate; @Test public void list2() { redisTemplate.opsForList().rightPush("userInfo",1); redisTemplate.opsForList().rightPush("userInfo","pan_junbiao的博客"); redisTemplate.opsForList().rightPush("userInfo","https://blog.csdn.net/pan_junbiao"); redisTemplate.opsForList().rightPush("userInfo","您好,欢迎访问 pan_junbiao的博客"); System.out.println("用户编号:" + redisTemplate.opsForList().index("userInfo",0)); System.out.println("用户名称:" + redisTemplate.opsForList().index("userInfo",1)); System.out.println("博客地址:" + redisTemplate.opsForList().index("userInfo",2)); System.out.println("博客信息:" + redisTemplate.opsForList().index("userInfo",3)); }
返回存储在键中的列表的长度。如果键不存在,则将其解释为空列表,并返回0。如果key存在的值不是列表,则返回错误。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void list3() { String[] user = new String[]{"1","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"}; redisTemplate.opsForList().leftPushAll("user",user); System.out.println("列表的长度:" + redisTemplate.opsForList().size("user")); }
执行结果:
在列表中 index 的位置设置 value。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void list4() { String[] user = new String[]{"1","pan_junbiao的博客","https://blog.csdn.net/pan_junbiao"}; redisTemplate.opsForList().rightPushAll("user",user); System.out.println(redisTemplate.opsForList().range("user",0,-1)); redisTemplate.opsForList().set("user",2,"您好,欢迎访问 pan_junbiao的博客"); System.out.println(redisTemplate.opsForList().range("user",0,-1)); }
执行结果:
根据下标获取列表中的值(下标从0开始)。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void list2() { redisTemplate.opsForList().rightPush("userInfo",1); redisTemplate.opsForList().rightPush("userInfo","pan_junbiao的博客"); redisTemplate.opsForList().rightPush("userInfo","https://blog.csdn.net/pan_junbiao"); redisTemplate.opsForList().rightPush("userInfo","您好,欢迎访问 pan_junbiao的博客"); System.out.println("用户编号:" + redisTemplate.opsForList().index("userInfo",0)); System.out.println("用户名称:" + redisTemplate.opsForList().index("userInfo",1)); System.out.println("博客地址:" + redisTemplate.opsForList().index("userInfo",2)); System.out.println("博客信息:" + redisTemplate.opsForList().index("userInfo",3)); }
执行结果:
从键中存储的列表中删除第一个计数事件等于给定“count”值的元素。其中,参数count的含义如下:
count=0:删除等于value的所有元素。
count>0:删除等于从头到尾移动的值的元素。
count<0:删除等于从尾到头移动的值的元素。
以下代码用于删除列表中第一次出现的值:
@Autowired private RedisTemplate redisTemplate; @Test public void list5() { String[] user = new String[]{"1","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"}; redisTemplate.opsForList().rightPushAll("user",user); System.out.println(redisTemplate.opsForList().range("user",0,-1)); //将删除列表中第一次出现的pan_junbiao的博客 redisTemplate.opsForList().remove("user",1,"pan_junbiao的博客"); System.out.println(redisTemplate.opsForList().range("user",0,-1)); }
执行结果:
leftPop方法:弹出最左边的元素,弹出之后该值在列表中将不复存在。
rightPop方法:弹出最右边的元素,弹出之后该值在列表中将不复存在。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void list6() { String[] user = new String[]{"1","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"}; redisTemplate.opsForList().rightPushAll("user",user); System.out.println(redisTemplate.opsForList().range("user",0,-1)); //弹出最右边的元素,弹出之后该值在列表中将不复存在 System.out.println(redisTemplate.opsForList().rightPop("user")); System.out.println(redisTemplate.opsForList().range("user",0,-1)); }
执行结果:
Redis 中的 hash(哈希)是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象。value 中存放的是结构化的对象。利用这样数据结果,可以方便地操作其中的某个字段。比如在“单点登录”时,可以用这种数据结构存储用户信息。以 CookieId 作为 key,设置30分钟为缓存过期时间,能很好地模拟出类似 Session 的效果。
putAll方法:用 m 中提供的多个散列字段设置到 key 对应的散列表中。
entries方法:根据密钥获取整个散列存储。具体用法见以下代码:
/** * Redis操作哈希(Hash) * @author pan_junbiao **/ @SpringBootTest public class HashTest { @Autowired private RedisTemplate redisTemplate; @Test public void hash2() { MapuserMap = new HashMap<>(); userMap.put("userName","pan_junbiao的博客"); userMap.put("blogRemark","您好,欢迎访问 pan_junbiao的博客"); redisTemplate.opsForHash().putAll("userHash",userMap); System.out.println(redisTemplate.opsForHash().entries("userHash")); } }
执行结果:
put方法:设置 hashKey 的值。
get方法:从键中的散列获取给定 hashKey 的值。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void hash3() { redisTemplate.opsForHash().put("userHash","userName","pan_junbiao的博客"); redisTemplate.opsForHash().put("userHash","blogUrl","https://blog.csdn.net/pan_junbiao"); redisTemplate.opsForHash().put("userHash","blogRemark","您好,欢迎访问 pan_junbiao的博客"); System.out.println("用户名称:" + redisTemplate.opsForHash().get("userHash","userName")); System.out.println("博客地址:" + redisTemplate.opsForHash().get("userHash","blogUrl")); System.out.println("博客信息:" + redisTemplate.opsForHash().get("userHash","blogRemark")); }
执行结果:
values方法:根据密钥获取整个散列存储的值。
keys方法:根据密钥获取整个散列存储的键。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void hash4() { redisTemplate.opsForHash().put("userHash","userName","pan_junbiao的博客"); redisTemplate.opsForHash().put("userHash","blogRemark","您好,欢迎访问 pan_junbiao的博客"); System.out.println("散列存储的值:" + redisTemplate.opsForHash().values("userHash")); System.out.println("散列存储的键:" + redisTemplate.opsForHash().keys("userHash")); }
执行结果:
hasKey方法:确定 hashKey 是否存在。
size方法:获取 key 所对应的散列表的大小个数。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void hash5() { redisTemplate.opsForHash().put("userHash","userName","pan_junbiao的博客"); redisTemplate.opsForHash().put("userHash","blogUrl","https://blog.csdn.net/pan_junbiao"); redisTemplate.opsForHash().put("userHash","blogRemark","您好,欢迎访问 pan_junbiao的博客"); System.out.println(redisTemplate.opsForHash().hasKey("userHash","userName")); System.out.println(redisTemplate.opsForHash().hasKey("userHash","age")); System.out.println(redisTemplate.opsForHash().size("userHash")); }
执行结果:
删除给定的 hashKeys。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void hash6() { redisTemplate.opsForHash().put("userHash","userName","pan_junbiao的博客"); redisTemplate.opsForHash().put("userHash","blogRemark","您好,欢迎访问 pan_junbiao的博客"); System.out.println(redisTemplate.opsForHash().delete("userHash","blogRemark")); System.out.println(redisTemplate.opsForHash().entries("userHash")); }
执行结果:
set 是存放不重复值的集合。利用 set 可以做全局去重复的功能。还可以进行交集、并集、差集等操作,也可用来实现计算共同喜好、全部的喜好、自己独有的喜好等功能。
Redis 的 set 是 string 类型的无序集合,通过散列表实现。
add方法:在无序集合中添加元素,返回添加个数;如果存在重复的则不进行添加。
members方法:返回集合中的所有成员。具体用法见以下代码:
/** * Redis操作集合(Set) * @author pan_junbiao **/ @SpringBootTest public class SetTest { @Autowired private RedisTemplate redisTemplate; @Test public void set1() { String[] citys = new String[]{"北京","上海","广州","深圳"}; System.out.println(redisTemplate.opsForSet().add("citySet",citys)); System.out.println(redisTemplate.opsForSet().add("citySet","香港","澳门","台湾")); //返回集合中的所有元素 System.out.println(redisTemplate.opsForSet().members("citySet")); } }
执行结果:
移除集合中一个或多个成员。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void set2() { String[] citys = new String[]{"北京","上海","广州","深圳"}; System.out.println(redisTemplate.opsForSet().add("citySet",citys)); System.out.println(redisTemplate.opsForSet().remove("citySet",citys)); }
执行结果:
移除并返回集合中的一个随机元素。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void set3() { String[] citys = new String[]{"北京","上海","广州","深圳"}; System.out.println(redisTemplate.opsForSet().add("citySet",citys)); System.out.println(redisTemplate.opsForSet().pop("citySet")); System.out.println(redisTemplate.opsForSet().members("citySet")); }
执行结果:
将 member 元素移动。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void set4() { String[] citys = new String[]{"北京","上海","广州","深圳"}; System.out.println(redisTemplate.opsForSet().add("citySet",citys)); System.out.println(redisTemplate.opsForSet().move("citySet","深圳","citySet2")); System.out.println(redisTemplate.opsForSet().members("citySet")); System.out.println(redisTemplate.opsForSet().members("citySet2")); }
执行结果:
用于遍历 Set。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void set5() { String[] citys = new String[]{"北京","上海","广州","深圳"}; System.out.println(redisTemplate.opsForSet().add("citySet",citys)); Cursor
执行结果:
Set
Set
Set
具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void set6() { String[] city1 = new String[]{"北京", "上海", "广州", "深圳", "昆明"}; String[] city2 = new String[]{"北京", "深圳", "昆明", "成都"}; System.out.println(redisTemplate.opsForSet().add("citySet1", city1)); System.out.println(redisTemplate.opsForSet().add("citySet2", city2)); //返回集合中的所有元素 System.out.println("城市集合1:" + redisTemplate.opsForSet().members("citySet1")); System.out.println("城市集合2:" + redisTemplate.opsForSet().members("citySet2")); //求交集、并集、差集(方式一) System.out.println("求交集、并集、差集(方式一):"); System.out.println("交集:" + redisTemplate.opsForSet().intersect("citySet1","citySet2")); System.out.println("并集:" + redisTemplate.opsForSet().union("citySet1","citySet2")); System.out.println("差集:" + redisTemplate.opsForSet().difference("citySet1","citySet2")); //求交集、并集、差集(方式二) redisTemplate.opsForSet().intersectAndStore("citySet1","citySet2", "intersectCity"); redisTemplate.opsForSet().unionAndStore("citySet1","citySet2", "unionCity"); redisTemplate.opsForSet().differenceAndStore("citySet1","citySet2", "differenceCity"); System.out.println("求交集、并集、差集(方式二):"); System.out.println("交集:" + redisTemplate.opsForSet().members("intersectCity")); System.out.println("并集:" + redisTemplate.opsForSet().members("unionCity")); System.out.println("差集:" + redisTemplate.opsForSet().members("differenceCity")); }
执行结果:
zset(Sorted Set 有序集合)也是 string 类型元素的集合,且不允许重复的成员。每个元素都会关联一个 double 类型的分数。可以通过分数将该集合中的成员从小到大进行排序。
虽然 zset 的成员是唯一的,但是权重参数分数(score)可以重复。集合中的元素能够按 score 进行排列。它可以用来做排行榜应用、取TOP/N、延时任务、范围查找等。
增加一个有序集合。具体用法见以下代码:
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.DefaultTypedTuple; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ZSetOperations; import java.util.HashSet; import java.util.Set; /** * Redis操作有序集合(Sorted Set) * @author pan_junbiao **/ @SpringBootTest public class SortedSetTest { @Autowired private RedisTemplate redisTemplate; @Test public void Zset1() { ZSetOperations.TypedTupleobjectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set > typles = new HashSet >(); typles.add(objectTypedTuple1); typles.add(objectTypedTuple2); typles.add(objectTypedTuple3); System.out.println(redisTemplate.opsForZSet().add("typles",typles)); System.out.println(redisTemplate.opsForZSet().range("typles",0,-1)); } }
执行结果:
新增一个有序集合,存在的话为false,不存在的话为true。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset2() { System.out.println(redisTemplate.opsForZSet().add("zset2", "pan_junbiao的博客_01", 9.6)); System.out.println(redisTemplate.opsForZSet().add("zset2", "pan_junbiao的博客_01", 9.6)); }
执行结果:
从有序集合中移除一个或者多个元素。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset3() { System.out.println(redisTemplate.opsForZSet().add("zset3", "pan_junbiao的博客_01", 1.0)); System.out.println(redisTemplate.opsForZSet().add("zset3", "pan_junbiao的博客_02", 1.0)); System.out.println(redisTemplate.opsForZSet().range("zset3", 0, -1)); System.out.println(redisTemplate.opsForZSet().remove("zset3", "pan_junbiao的博客_02")); System.out.println(redisTemplate.opsForZSet().range("zset3", 0, -1)); }
执行结果:
返回有序集中指定成员的排名,其中有序集成员按分数值递增(从小到大)顺序排列。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset4() { System.out.println(redisTemplate.opsForZSet().add("zset4", "pan_junbiao的博客_01",9.6)); System.out.println(redisTemplate.opsForZSet().add("zset4", "pan_junbiao的博客_02",1.5)); System.out.println(redisTemplate.opsForZSet().add("zset4", "pan_junbiao的博客_03",7.4)); System.out.println(redisTemplate.opsForZSet().range("zset4", 0, -1)); System.out.println(redisTemplate.opsForZSet().rank("zset4", "pan_junbiao的博客_02")); }
执行结果:
注意:结果中的0表示第一(最小)。
range方法:通过索引区间返回有序集合成指定区间内的成员,其中有序集成员按分数值递增(从小到大)顺序排列。
rangeByScore方法:通过分数区间返回有序集合成指定区间内的成员,其中有序集成员按分数值递增(从小到大)顺序排列。
具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset5() { ZSetOperations.TypedTupleobjectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set > typles = new HashSet >(); typles.add(objectTypedTuple1); typles.add(objectTypedTuple2); typles.add(objectTypedTuple3); System.out.println(redisTemplate.opsForZSet().add("zset5",typles)); System.out.println(redisTemplate.opsForZSet().range("zset5",0,-1)); System.out.println(redisTemplate.opsForZSet().rangeByScore("zset5", 0, 8)); }
执行结果:
count方法:通过分数返回有序集合指定区间内的成员个数。
size方法:获取有序集合的成员数。
具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset6() { ZSetOperations.TypedTupleobjectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set > typles = new HashSet >(); typles.add(objectTypedTuple1); typles.add(objectTypedTuple2); typles.add(objectTypedTuple3); redisTemplate.opsForZSet().add("zset6", typles); System.out.println("分数在0至8区间内的成员个数:" + redisTemplate.opsForZSet().count("zset6", 0, 8)); System.out.println("有序集合的成员数:" + redisTemplate.opsForZSet().size("zset6")); }
执行结果:
获取指定成员的score值。具体用法见以下代码:
@Test public void Zset7() { redisTemplate.opsForZSet().add("zset7", "pan_junbiao的博客_01", 9.6); redisTemplate.opsForZSet().add("zset7", "pan_junbiao的博客_02", 1.5); redisTemplate.opsForZSet().add("zset7", "pan_junbiao的博客_03", 7.4); System.out.println("pan_junbiao的博客_01的分数:" + redisTemplate.opsForZSet().score("zset7", "pan_junbiao的博客_01")); System.out.println("pan_junbiao的博客_02的分数:" + redisTemplate.opsForZSet().score("zset7", "pan_junbiao的博客_02")); System.out.println("pan_junbiao的博客_03的分数:" + redisTemplate.opsForZSet().score("zset7", "pan_junbiao的博客_03")); }
执行结果:
移除指定索引位置的成员,有序集合成员按照分数值递增(从小到大)顺序排列。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset8() { ZSetOperations.TypedTupleobjectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set > tuples = new HashSet >(); tuples.add(objectTypedTuple1); tuples.add(objectTypedTuple2); tuples.add(objectTypedTuple3); System.out.println(redisTemplate.opsForZSet().add("zset8", tuples)); System.out.println(redisTemplate.opsForZSet().range("zset8", 0, -1)); System.out.println(redisTemplate.opsForZSet().removeRange("zset8", 1, 5)); System.out.println(redisTemplate.opsForZSet().range("zset8", 0, -1)); }
执行结果:
遍历 zset。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset9() { ZSetOperations.TypedTupleobjectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set > tuples = new HashSet >(); tuples.add(objectTypedTuple1); tuples.add(objectTypedTuple2); tuples.add(objectTypedTuple3); System.out.println(redisTemplate.opsForZSet().add("zset9", tuples)); Cursor > cursor = redisTemplate.opsForZSet().scan("zset9", ScanOptions.NONE); while (cursor.hasNext()) { ZSetOperations.TypedTuple
执行结果:
The above is the detailed content of How SpringBoot uses RedisTemplate to operate Redis data types. For more information, please follow other related articles on the PHP Chinese website!