SpringBoot uses RedisTemplate to operate 5 data types of Redis

Spring encapsulates RedisTemplate to operate Redis, which supports all Redis native APIs. The operation methods for five data structures are defined in RedisTemplate.

  • opsForValue(): Operation string.
  • opsForList(): Operation list.
  • opsForHash(): Operation hash.
  • opsForSet(): Operation set.
  • opsForZSet(): Operate an ordered set.

The following examples are used to understand and apply these methods. It is important to note that the data must be cleared after running the above method, otherwise multiple runs will result in repeated data operations.

(1) Use Maven to add dependent 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, and 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 is the most basic data type of Redis. A "Key" of a String corresponds to a "Value", that is, a key-value pair. String is binary safe and can store any data (such as pictures or serialized objects). The value can store up to 512MB of data. Generally used for the cache of some complex counting functions. RedisTemplate provides the following methods to manipulate String.

1.1 void set(K key, V value);V get(Object key)

See the following code for specific usage:

/**
 * 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"));
    }
}

Results of the:

1.2 void set(K key, V value, long timeout, TimeUnit unit)

The following code is invalid for 3s. The query has results within 3s, and the query returns 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();
    }
}

Results of the:

1.3 V getAndSet(K key, V value)

Set the string of the key and return 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);
}

Results of the:

1.4 Integer append(K key, V value)

If the key already exists and is a string, the command appends the value to the end of the string. If the key does not exist, it will be created and set to an empty string, so append is similar to set 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"));
}

Results of the:

Note: You must pay attention to the deserialization configuration here, otherwise an error will be reported.

1.5 Long size(K key)

Return the length of the value corresponding to the key, see the following code:

@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"));
}

Results of the:

 

2. List

The Redis list is a simple list of strings, sorted in the order of insertion. You can add an element to the head (left) or tail (right) of the list.

Using the list data results, you can do a simple message queue function. You can also use the Irange command to do the paging function based on Reids, with excellent performance.

2.1 Long leftPushAll(K key, V... values);Long rightPushAll(K key, V... values)

leftPushAll method: means to insert an array into the list.

rightPushAll method: means adding elements to the rightmost of the list in batches. 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));
    }
}

Results of the:

2.2 Long leftPush(K key, V value);Long rightPush(K key, V value)

leftPush method: Insert all specified values ​​at the head of the key list. If the key does not exist, it is created as an empty list (inserted from the left) before performing the push operation.

rightPush method: insert all specified values ​​at the end of the key list. If the key does not exist, it is created as an empty list (inserted from the right) before performing the push operation. See the following code for specific usage:

@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));
}

Results of the:

2.3 Long size(K key)

Returns the length of the list stored in the key. If the key does not exist, it is interpreted as an empty list and 0 is returned. If the value of the key is not a list, an error is returned. See the following code for specific usage:

@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"));
}

Results of the:

2.4 void set(K key, long index, V value)

Set the value at the index position in the list. See the following code for specific usage:

@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));
}

Results of the:

2.5 V index(K key, long index)

Get the value in the list according to the subscript (subscript starts from 0). See the following code for specific usage:

@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));
}

Results of the:

2.6 Long remove(K key, long count, Object value)

From the list stored in the key, delete the first count event of the element with the given "count" value. Among them, the meaning of the parameter count is as follows:

  • count=0: delete all elements equal to value.
  • count>0: delete elements equal to the value moved from beginning to end.
  • count<0: delete elements equal to the value moved from the end to the beginning.

The following code is used to delete the first occurrence of the value in the list:

@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));
}

Results of the:

2.7 V leftPop(K key);V rightPop(K key)

leftPop method: Pop up the leftmost element, and the value will no longer exist in the list after being popped.

rightPop method: pop up the rightmost element, and the value will no longer exist in the list after popping up. See the following code for specific usage:

@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));
}

Results of the:

 

3. Hash

The hash in Redis is a mapping table between field and value of string type, and hash is particularly suitable for storing objects. What is stored in value is a structured object. Using such data results, you can easily manipulate one of the fields. For example, in "single sign-on", you can use this data structure to store user information. Using CookieId as the key and setting 30 minutes as the cache expiration time can well simulate the effect similar to Session.

3.1 void putAll(H key, Map<? extends HK, ? extends HV> m);Map<HK, HV> entries(H key)

putAll method: Use multiple hash fields provided in m to set the hash table corresponding to the key.

Entries method: Get the entire hash storage according to the key. See the following code for specific usage:

/**
 * Redis操作哈希(Hash)
 * @author pan_junbiao
 **/
@SpringBootTest
public class HashTest
{
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void hash1()
    {
        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"));
    }
}

Results of the:

3.2 void put(H key, HK hashKey, HV value);HV get(H key, Object hashKey)

put method: set the value of hashKey.

get method: Get the value of a given hashKey from the hash in the key. See the following code for specific usage:

@Autowired
private RedisTemplate redisTemplate;

@Test
public void hash2()
{
    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"));
}

Results of the:

3.3 List<HV> values(H key);Set<HK> keys(H key)

The values ​​method: Get the value of the entire hash storage according to the key.

The keys method: Get the key of the entire hash storage according to the key. See the following code for specific usage:

@Autowired
private RedisTemplate redisTemplate;

@Test
public void hash3()
{
    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"));
}

Results of the:

3.4 Boolean hasKey(H key, Object hashKey);Long size(H key)

hasKey method: Determine whether hashKey exists.

size method: Get the size of the hash table corresponding to the key. See the following code for specific usage:

@Autowired
private RedisTemplate redisTemplate;

@Test
public void hash4()
{
    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"));
}

Results of the:

3.5 Long delete(H key, Object... hashKeys)

Delete the given hashKeys. See the following code for specific usage:

@Autowired
private RedisTemplate redisTemplate;

@Test
public void hash5()
{
    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"));
}

Results of the:

 

4. Set

set is a collection of unique values. Use set to do global de-duplication function. You can also perform operations such as intersection, union, and difference, and can also be used to calculate common preferences, all preferences, and your own unique preferences.

Redis set is an unordered collection of string type, implemented through a hash table.

4.1 Long add(K key, V... values);Set<V> members(K key)

add method: add elements to the unordered collection and return the number of additions; if there are duplicates, do not add them.

members method: returns all members in the collection. See the following code for specific usage:

/**
 * 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"));
    }
}

Results of the:

4.2 Long remove(K key, Object... values)

Remove one or more members from the collection. See the following code for specific usage:

@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));
}

Results of the:

4.3 V pop (K key)

Remove and return a random element in the set. See the following code for specific usage:

@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"));
}

Results of the:

4.4 Boolean move(K key, V value, K destKey)

Move the member element. See the following code for specific usage:

@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"));
}

Results of the:

4.5 Cursor<V> scan(K key, ScanOptions options)

Used to traverse the Set. See the following code for specific usage:

@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());
    }
}

Results of the:

4.6 Intersection, Union, Difference

Set<V> intersect(K key1, K key2) method, Long intersectAndStore(K key1, K key2, K destKey) method: intersection.

Set<V> union(K key1, K key2) method, Long unionAndStore(K key1, K key2, K destKey) method: union.

Set<V> difference(K key1, K key2)方法、Long differenceAndStore(K key1, K key2, K destKey)方法:差集。

See the following code for specific usage:

@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"));
}

Results of the:

 

5. Sorted Set

zset (Sorted Set ordered set) is also a set of string type elements, and duplicate members are not allowed. Each element will be associated with a double type score. The members in the set can be sorted from small to large by score.

The members of zset are unique, but the weight parameter score (score) can be repeated. The elements in the set can be arranged by score. It can be used for ranking applications, TOP/N fetching, delayed tasks, range searching, etc.

5.1 Long add(K key, Set<ZSetOperations.TypedTuple<V>> tuples)

Add an ordered collection. See the following code for specific usage:

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));
    }
}

Results of the:

5.2 Boolean add(K key, V value, double score)

Add an ordered set, false if it exists, and true if it does not exist. See the following code for specific usage:

@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));
}

Results of the:

5.3 Long remove(K key, Object... values)

Remove one or more elements from an ordered set. See the following code for specific usage:

@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));
}

Results of the:

5.4 Long rank(K key, Object value)

Returns the ranking of the specified member in the ordered set, where the members of the ordered set are arranged in the order of increasing points (from small to large). See the following code for specific usage:

@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"));
}

Results of the:

Note: The 0 in the result means the first (smallest).

5.5 Set<V> range(K key, long start, long end);Set<V> rangeByScore(K key, double score1, double score2)

Range method: Return the ordered set into the members in the specified interval through the index interval, and the ordered set members are arranged in the order of increasing score value (from small to large).

RangeByScore method: Return the ordered set into the members in the specified interval through the score interval, and the ordered set members are arranged in the order of increasing score value (from small to large).

See the following code for specific usage:

@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));
}

Results of the:

5.6 Long count(K key, double score1, double score2);Long size(K key)

Count method: returns the number of members in the specified interval of the ordered set by score.

size method: Get the number of members in an ordered set.

See the following code for specific usage:

@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"));
}

Results of the:

5.7 Double score(K key, Object o)

Get the score value of the specified member. See the following code for specific usage:

@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"));
}

Results of the:

5.8 Long removeRange(K key, long start, long end)

Remove the members at the specified index position, and the ordered set members are arranged in the order of increasing score (from small to large). See the following code for specific usage:

@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));
}

Results of the:

5.9 Cursor<ZSetOperations.TypedTuple<V>> scan(K key, ScanOptions options)

Traverse the zset. See the following code for specific usage:

@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());
    }
}

Results of the:

 

Guess you like

Origin blog.csdn.net/pan_junbiao/article/details/108882001