How SpringBoot uses RedisTemplate to operate Redis data types
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:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
Add Redis dependency:
<!-- Redis启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.3.3.RELEASE</version> </dependency>
(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 RedisTemplate<String, String> redisTemplate(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; } }
1. String (String)
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.
1.1 void set(K key, V value); V get(Object key)
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:
1.2 void set(K key, V value, long timeout, TimeUnit unit)
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:
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)
If the key already exists and is of string type, this command will append the new value to the end of the original string. When the key does not exist, it will be created and set to an empty string, which means that the append operation is similar to the set operation in this special case. See the following code for specific usage:
@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")); }
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"));
}
Copy after login
@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) * @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.
rightPush method: Inserts all specified values at the end of the key list. Before performing the push operation, if the key does not exist, create an empty list and insert the element to the right. For specific usage, see the following code:
@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)); }
2.3 Long size(K key)
返回存储在键中的列表的长度。如果键不存在,则将其解释为空列表,并返回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")); }
执行结果:
2.4 void set(K key, long index, V value)
在列表中 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)); }
执行结果:
2.5 V index(K key, long index)
根据下标获取列表中的值(下标从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)); }
执行结果:
2.6 Long remove(K key, long count, Object value)
从键中存储的列表中删除第一个计数事件等于给定“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)); }
执行结果:
2.7 V leftPop(K key);V rightPop(K key)
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)); }
执行结果:
3、哈希(Hash)
Redis 中的 hash(哈希)是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象。value 中存放的是结构化的对象。利用这样数据结果,可以方便地操作其中的某个字段。比如在“单点登录”时,可以用这种数据结构存储用户信息。以 CookieId 作为 key,设置30分钟为缓存过期时间,能很好地模拟出类似 Session 的效果。
3.1 void putAll(H key, Map extends HK, ? extends HV> m);Map entries(H key)
putAll方法:用 m 中提供的多个散列字段设置到 key 对应的散列表中。
entries方法:根据密钥获取整个散列存储。具体用法见以下代码:
/** * Redis操作哈希(Hash) * @author pan_junbiao **/ @SpringBootTest public class HashTest { @Autowired private RedisTemplate redisTemplate; @Test public void hash2() { Map<String,Object> userMap = new HashMap<>(); userMap.put("userName","pan_junbiao的博客"); userMap.put("blogRemark","您好,欢迎访问 pan_junbiao的博客"); redisTemplate.opsForHash().putAll("userHash",userMap); System.out.println(redisTemplate.opsForHash().entries("userHash")); } }
执行结果:
3.2 void put(H key, HK hashKey, HV value);HV get(H key, Object hashKey)
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")); }
执行结果:
3.3 List values(H key);Set keys(H key)
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")); }
执行结果:
3.4 Boolean hasKey(H key, Object hashKey);Long size(H key)
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")); }
执行结果:
3.5 Long delete(H key, Object... hashKeys)
删除给定的 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")); }
执行结果:
4、集合(Set)
set 是存放不重复值的集合。利用 set 可以做全局去重复的功能。还可以进行交集、并集、差集等操作,也可用来实现计算共同喜好、全部的喜好、自己独有的喜好等功能。
Redis 的 set 是 string 类型的无序集合,通过散列表实现。
4.1 Long add(K key, V... values);Set members(K key)
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")); } }
执行结果:
4.2 Long remove(K key, Object... values)
移除集合中一个或多个成员。具体用法见以下代码:
@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)); }
执行结果:
4.3 V pop(K key)
移除并返回集合中的一个随机元素。具体用法见以下代码:
@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")); }
执行结果:
4.4 Boolean move(K key, V value, K destKey)
将 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")); }
执行结果:
4.5 Cursor scan(K key, ScanOptions options)
用于遍历 Set。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void set5() { String[] citys = new String[]{"北京","上海","广州","深圳"}; System.out.println(redisTemplate.opsForSet().add("citySet",citys)); Cursor<Object> cursor = redisTemplate.opsForSet().scan("citySet", ScanOptions.NONE); while(cursor.hasNext()) { System.out.println(cursor.next()); } }
执行结果:
4.6 交集、并集、差集
Set
intersect(K key1, K key2)方法、Long intersectAndStore(K key1, K key2, K destKey)方法:交集。 Set
union(K key1, K key2)方法、Long unionAndStore(K key1, K key2, K destKey)方法:并集。 Set
difference(K key1, K key2)方法、Long differenceAndStore(K key1, K key2, K destKey)方法:差集。
具体用法见以下代码:
@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")); }
执行结果:
5、有序集合(Sorted Set)
zset(Sorted Set 有序集合)也是 string 类型元素的集合,且不允许重复的成员。每个元素都会关联一个 double 类型的分数。可以通过分数将该集合中的成员从小到大进行排序。
虽然 zset 的成员是唯一的,但是权重参数分数(score)可以重复。集合中的元素能够按 score 进行排列。它可以用来做排行榜应用、取TOP/N、延时任务、范围查找等。
5.1 Long add(K key, Set> tuples)
增加一个有序集合。具体用法见以下代码:
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.TypedTuple<String> objectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple<String> objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple<String> objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set<ZSetOperations.TypedTuple<String>> typles = new HashSet<ZSetOperations.TypedTuple<String>>(); 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)); } }
执行结果:
5.2 Boolean add(K key, V value, double score)
新增一个有序集合,存在的话为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)); }
执行结果:
5.3 Long remove(K key, Object... values)
从有序集合中移除一个或者多个元素。具体用法见以下代码:
@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)); }
执行结果:
5.4 Long rank(K key, Object value)
返回有序集中指定成员的排名,其中有序集成员按分数值递增(从小到大)顺序排列。具体用法见以下代码:
@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表示第一(最小)。
5.5 Set range(K key, long start, long end);Set rangeByScore(K key, double score1, double score2)
range方法:通过索引区间返回有序集合成指定区间内的成员,其中有序集成员按分数值递增(从小到大)顺序排列。
rangeByScore方法:通过分数区间返回有序集合成指定区间内的成员,其中有序集成员按分数值递增(从小到大)顺序排列。
具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset5() { ZSetOperations.TypedTuple<String> objectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple<String> objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple<String> objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set<ZSetOperations.TypedTuple<String>> typles = new HashSet<ZSetOperations.TypedTuple<String>>(); 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)); }
执行结果:
5.6 Long count(K key, double score1, double score2);Long size(K key)
count方法:通过分数返回有序集合指定区间内的成员个数。
size方法:获取有序集合的成员数。
具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset6() { ZSetOperations.TypedTuple<String> objectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple<String> objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple<String> objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set<ZSetOperations.TypedTuple<String>> typles = new HashSet<ZSetOperations.TypedTuple<String>>(); 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")); }
执行结果:
5.7 Double score(K key, Object o)
获取指定成员的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")); }
执行结果:
5.8 Long removeRange(K key, long start, long end)
移除指定索引位置的成员,有序集合成员按照分数值递增(从小到大)顺序排列。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset8() { ZSetOperations.TypedTuple<String> objectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple<String> objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple<String> objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set<ZSetOperations.TypedTuple<String>> tuples = new HashSet<ZSetOperations.TypedTuple<String>>(); 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)); }
执行结果:
5.9 Cursor> scan(K key, ScanOptions options)
遍历 zset。具体用法见以下代码:
@Autowired private RedisTemplate redisTemplate; @Test public void Zset9() { ZSetOperations.TypedTuple<String> objectTypedTuple1 = new DefaultTypedTuple<>("pan_junbiao的博客_01",9.6); ZSetOperations.TypedTuple<String> objectTypedTuple2 = new DefaultTypedTuple<>("pan_junbiao的博客_02",1.5); ZSetOperations.TypedTuple<String> objectTypedTuple3 = new DefaultTypedTuple<>("pan_junbiao的博客_03",7.4); Set<ZSetOperations.TypedTuple<String>> tuples = new HashSet<ZSetOperations.TypedTuple<String>>(); tuples.add(objectTypedTuple1); tuples.add(objectTypedTuple2); tuples.add(objectTypedTuple3); System.out.println(redisTemplate.opsForZSet().add("zset9", tuples)); Cursor<ZSetOperations.TypedTuple<Object>> cursor = redisTemplate.opsForZSet().scan("zset9", ScanOptions.NONE); while (cursor.hasNext()) { ZSetOperations.TypedTuple<Object> item = cursor.next(); System.out.println(item.getValue() + " 的分数值:" + item.getScore()); } }
执行结果:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

1. Start the [Start] menu, enter [cmd], right-click [Command Prompt], and select Run as [Administrator]. 2. Enter the following commands in sequence (copy and paste carefully): SCconfigwuauservstart=auto, press Enter SCconfigbitsstart=auto, press Enter SCconfigcryptsvcstart=auto, press Enter SCconfigtrustedinstallerstart=auto, press Enter SCconfigwuauservtype=share, press Enter netstopwuauserv , press enter netstopcryptS

PHP function bottlenecks lead to low performance, which can be solved through the following steps: locate the bottleneck function and use performance analysis tools. Caching results to reduce recalculations. Process tasks in parallel to improve execution efficiency. Optimize string concatenation, use built-in functions instead. Use built-in functions instead of custom functions.

The caching strategy in GolangAPI can improve performance and reduce server load. Commonly used strategies are: LRU, LFU, FIFO and TTL. Optimization techniques include selecting appropriate cache storage, hierarchical caching, invalidation management, and monitoring and tuning. In the practical case, the LRU cache is used to optimize the API for obtaining user information from the database. The data can be quickly retrieved from the cache. Otherwise, the cache can be updated after obtaining it from the database.

There are performance differences between Erlang and Go. Erlang excels at concurrency, while Go has higher throughput and faster network performance. Erlang is suitable for systems that require high concurrency, while Go is suitable for systems that require high throughput and low latency.

In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

Using Redis cache can greatly optimize the performance of PHP array paging. This can be achieved through the following steps: Install the Redis client. Connect to the Redis server. Create cache data and store each page of data into a Redis hash with the key "page:{page_number}". Get data from cache and avoid expensive operations on large arrays.

First you need to set the system language to Simplified Chinese display and restart. Of course, if you have changed the display language to Simplified Chinese before, you can just skip this step. Next, start operating the registry, regedit.exe, directly navigate to HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlNlsLanguage in the left navigation bar or the upper address bar, and then modify the InstallLanguage key value and Default key value to 0804 (if you want to change it to English en-us, you need First set the system display language to en-us, restart the system and then change everything to 0409) You must restart the system at this point.

Yes, Navicat can connect to Redis, which allows users to manage keys, view values, execute commands, monitor activity, and diagnose problems. To connect to Redis, select the "Redis" connection type in Navicat and enter the server details.
