It takes about 15 minutes to read the article

I have shared Redis interview questions in previous posts, see Redis Overview, Interview questions. In this article I will focus on how to use Redis in SpringBoot.

As a tool to store data, the most common and most commonly used database types used in development are divided into relational database and non-relational database. I won’t introduce their differences here

The most representative relational database is Oracel, Microsoft SQL Server, Microsoft Access and MySQL, etc.

Non-relational databases are represented by MongoDB, Redis, Memcache and so on.

Redis is currently the most widely used key-value database, Redis supports richer data structures than other NOSQL, see Redis overview, interview questions.

1. The advantages of Redis

  • Redis database is a cache database, used to store frequently used data, so as to reduce the number of times to access the database, improve operation efficiency.
  • In terms of access speed, the memory read speed is about 10W. If you have higher requirements on performance, you can cluster redis.

2. The use of Redis

1. Introduce Redis dependencies provided by SpringBoot

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
Copy the code

2. Add the configuration file

Add the following configuration to the application.yml file:

Spring: redis: # redis server address6379Password: XXX lettuce: pool: # redis maximum number of connections, default8
        max-active: 100# redis Max block wait time defaults to -1Max-wait: PT10S # redis Maximum number of idle connections. Default8
        max-idle: 30# redis Minimum number of free connections, default0
        min-idle: 1# redis database connection timeout: PT10S # redis database index0
    database: 2
Copy the code

Add the Redis configuration class

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();
        MyStringRedisSerializer myStringRedisSerializer=new MyStringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(myStringRedisSerializer);
        redisTemplate.setValueSerializer(myStringRedisSerializer);
        returnredisTemplate; }}Copy the code
public class MyStringRedisSerializer implements RedisSerializer<Object> {
    private final Charset charset;

    public MyStringRedisSerializer(a) {
        this(StandardCharsets.UTF_8);
    }

    public MyStringRedisSerializer(Charset charset) {
        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
    }

    @Override
    public String deserialize(byte[] bytes) {
        return (bytes == null ? null : new String(bytes, charset));
    }

    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return new byte[0];
        }
        if(object instanceof String){
            return object.toString().getBytes(charset);
        }else {
            String string = JSON.toJSONString(object);
            returnstring.getBytes(charset); }}}Copy the code

4, the use of

** The RedisTemplate is automatically injected first. **Spring’s methods for Redis are wrapped in the RedisTemplate.

@Autowired
private RedisTemplate<String, Object> redisTemplate;
Copy the code
@Test
public void testRedisInsertObject(a) {
    User user = new User(UUID.randomUUID().toString(), "Zhang".18);
    redisTemplate.opsForValue().set(user.getId(), user);
}
Copy the code

You can see that the data has been added to Redis:

If you want to create a RedisTemplate each time you use it, you can encapsulate the methods in the RedisTemplate as a utility class.

package com.gsy.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/ * * *@author: ifknow
 * @description: Redis utility class */
@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    / * * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the key related operations -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * /

    /** * Whether key ** exists@param key
     * @return java.lang.Boolean
     */
    public Boolean hasKey(String key) {
        if (null == key) {
            return false;
        }
        return redisTemplate.hasKey(key);
    }

    /** * delete key **@param key
     * @returnBoolean Returns true on success false */ on failure
    public Boolean delete(String key) {
        if (null == key) {
            return false;
        }
        return redisTemplate.delete(key);
    }

    /** * Delete key ** in batches@param keys
     * @returnLong returns the number of successfully deleted keys */
    public Long delete(Collection<String> keys) {
        return redisTemplate.delete(keys);
    }


    /** * Sets the expiration time **@param key
     * @param timeout
     * @param unit
     * @return java.lang.Boolean
     */
    public Boolean expire(String key, long timeout, TimeUnit unit) {
        if (null == key || null == unit) {
            return false;
        }
        return redisTemplate.expire(key, timeout, unit);
    }

    /** * find a matching key **@param pattern
     * @return java.util.Set<java.lang.String>
     */
    public Set<String> keys(String pattern) {
        if (null == pattern) {
            return null;
        }
        return redisTemplate.keys(pattern);
    }


    /** * Remove the expiration time of the key, the key will persist **@param key
     * @return java.lang.Boolean
     */
    public Boolean persist(String key) {
        if (null == key) {
            return false;
        }
        return redisTemplate.persist(key);
    }

    /** * Returns the remaining expiration time of the key **@param key
     * @param unit
     * @returnJava.lang. Long Returns -2 when the key does not exist. If the key exists but the remaining lifetime is not set, -1 is returned. Otherwise, return the remaining lifetime of the key in seconds */
    public Long getExpire(String key, TimeUnit unit) {
        if (null == key || null == unit) {
            throw new NullPointerException("Key or TomeUnit cannot be empty");
        }
        return redisTemplate.getExpire(key, unit);
    }

    / * * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the String data type -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * /

    /** * Sets the specified key value **@param key
     * @param value
     */
    public void set(String key, Object value) {

        if (null == key || null == value) {
            return;
        }
        redisTemplate.opsForValue().set(key, value);
    }

    /** * Sets the key value and expiration time **@param key
     * @param value
     * @param time
     * @param unit
     */
    public void set(String key, Object value, long time, TimeUnit unit) {

        if (null == key || null == value || null == unit) {
            return;
        }
        redisTemplate.opsForValue().set(key, value, time, unit);
    }

    /** * Set the value of the key and set the expiration time * Return false if the key does not exist * Return true if the key does not exist@param key
     * @param value
     * @param time
     * @param unit
     * @return java.lang.Boolean
     */
    public Boolean setifAbsen(String key, Object value, long time, TimeUnit unit) {

        if (null == key || null == value || null == unit) {
            throw new NullPointerException("Key, value, unit cannot be empty");
        }
        return redisTemplate.opsForValue().setIfAbsent(key, value, time, unit);
    }

    /** * gets the Value of the specified Key. If the Value associated with the Key is not a string, Redis will throw an exception, * because the GET command can only be used to GET a string Value, and returns null * * if the Key does not exist@param key
     * @return java.lang.Object
     */
    public Object get(String key) {

        if (null == key) {
            return null;
        }
        return redisTemplate.opsForValue().get(key);
    }

    /** * get the value of the key and set the new value. * *@param key
     * @param value
     * @return java.lang.Object
     */
    public Object getSet(String key, Object value) {

        if (null == key) {
            return null;
        }
        return redisTemplate.opsForValue().getAndSet(key, value);
    }

    /** * Get value ** from key **@param keys
     * @return java.util.List<java.lang.Object>
     * @throws
     * @Author: small huo *@UpdateUser:
     * @Version: 0.0.1 * /
    public List<Object> mget(Collection<String> keys) {

        if (null == keys) {
            return Collections.emptyList();
        }
        return redisTemplate.opsForValue().multiGet(keys);
    }

    /** * increment increment of the Key's Value atomically. If the Key does not exist, its initial value is 0 and its value is increment after incrby. * If the Value of Value cannot be converted to an integer Value, such as Hi, the operation will fail and an exception will be thrown. If the operation succeeds, the added value is returned. * *@param key
     * @param increment
     * @return long
     * @throws* /
    public long incrby(String key, long increment) {
        if (null == key) {
            throw new NullPointerException("Key cannot be empty");
        }
        return redisTemplate.opsForValue().increment(key, increment);
    }

    /** * Will specify a reduction in atomicity of the Key's Value. If the Key does not exist, it will have an initial value of 0 and * will have a value of -decrement after decrby. If the Value of Value cannot be converted to an integer Value, * such as Hi, the operation will fail and the appropriate exception will be thrown. If the operation succeeds, the reduced value is returned. * *@param key
     * @param decrement
     * @return java.lang.Long
     */
    public Long decrby(String key, long decrement) {
        if (null == key) {
            throw new NullPointerException("Key cannot be empty");
        }
        return redisTemplate.opsForValue().decrement(key, decrement);
    }

    /** * If the Key already exists, the APPEND command appends the data of the argument Value to the end of the existing Value. If the Key does not exist, the * APPEND command creates a new Key/Value. Returns the string length of the appended Value. * *@param key
     * @param value
     * @return java.lang.Integer
     */
    public Integer append(String key, String value) {
        if (key == null) {
            throw new NullPointerException("Key cannot be empty");
        }
        return redisTemplate.opsForValue().append(key, value);
    }
//****************** Hash data type *********************

    /** * Get the specified value ** by key and field@param key
     * @param field
     * @return java.lang.Object
     */
    public Object hget(String key, Object field) {
        if (null == key || null == field) {
            return null;
        }
        return redisTemplate.opsForHash().get(key, field);
    }

    /** * Sets the Field/Value pair for the specified Key. If the Key does not exist, this command creates a new Key to store the Field/Value pair in the parameter. * If the Field in the parameter already exists in the Key, the new Value overwrites the original Value. * Returns 1 to indicate that the new Field is set to a new value, and 0 to indicate that the Field already exists, overwriting the old value with the new value. * *@param key
     * @param field
     * @param value
     */
    public void hset(String key, Object field, Object value) {
        if (null == key || null == field) {
            return;
        }
        redisTemplate.opsForHash().put(key, field, value);
    }

    /** * Returns true if the specified Field in the specified Key exists, false if the specified Field or Key does not exist. * *@param key
     * @param field
     * @return java.lang.Boolean
     */
    public Boolean hexists(String key, Object field) {
        if (null == key || null == field) {
            return false;
        }
        return redisTemplate.opsForHash().hasKey(key, field);
    }

    /** * Removes the specified fields from the Hashes Value of the specified Key. If non-existing fields are ignored, * returns the actual number of fields removed. If the Key does not exist, it is treated as empty Hashes and 0 is returned. * *@param key
     * @param fields
     * @return java.lang.Long
     */
    public Long hdel(String key, Object... fields) {
        if (null == key || null == fields || fields.length == 0) {
            return 0L;
        }
        return redisTemplate.opsForHash().delete(key, fields);
    }


    /** * Get all fields and values ** by key@param key
     * @return java.util.Map<java.lang.Object, java.lang.Object>
     */
    public Map<Object, Object> hgetall(String key) {
        if (key == null) {
            return null;
        }
        return redisTemplate.opsForHash().entries(key);
    }

    /** * sets the Field/Value pairs given in the argument pair by pair. If one of the fields already exists, the new value overwrites the old value. * If the Key does not exist, create a new Key and set the Field/Value in the parameters. * *@param key
     * @param hash
     */
    public void hmset(String key, Map<String, Object> hash) {

        if (null == key || null == hash) {
            return;
        }
        redisTemplate.opsForHash().putAll(key, hash);
    }

    /** * Gets a set of Values associated with the Fields specified in the argument in the order Fields were requested. * If the requested Field does not exist, the value corresponding to its value is null. * *@param key
     * @param fields
     * @return java.util.List<java.lang.Object>
     */
    public List<Object> hmget(String key, Collection<Object> fields) {

        if (null == key || null == fields) {
            return null;
        }

        return redisTemplate.opsForHash().multiGet(key, fields);
    }

    /** * The corresponding key field increases the corresponding value **@param key
     * @param field
     * @param increment
     * @return java.lang.Long
     */
    public Long hIncrBy(String key, Object field, long increment) {
        if (null == key || null == field) {
            throw new NullPointerException("Key or field cannot be empty");
        }
        return redisTemplate.opsForHash().increment(key, field, increment);

    }
    //***************List Data type ***************

    /** * adds an element to the left of the list. If the Key does not exist, the command creates an empty linked list associated with the Key prior to insertion, and inserts data from the head of the list later. * This command will throw an exception if the Value of the key is not of a linked list type. Success returns the number of elements in the list after insertion. * *@param key
     * @paramSTRS can be either a string or an array of strings *@returnJava.lang. Long returns the number of values for the operation */
    public Long lpush(String key, Object... strs) {
        if (null == key) {
            return 0L;
        }
        return redisTemplate.opsForList().leftPushAll(key, strs);
    }

    /** * adds elements to the right of the list. If the Key does not exist, the command creates an empty linked list associated with the Key prior to insertion, and inserts data from the end of the list later. * This command will throw an exception if the Value of the key is not of a linked list type. Success returns the number of elements in the list after insertion. * *@param key
     * @paramSTRS can be either a string or an array of strings *@returnJava.lang. Long returns the number of values for the operation */
    public Long rpush(String key, Object... strs) {
        if (null == key) {
            return 0L;
        }
        return redisTemplate.opsForList().rightPushAll(key, strs);
    }

    /** * returns and pops the first element in the list associated with the specified Key, the header element. If the Key does not exist, * returns nil. The LPOP command performs two steps: the first removes the element to the left of the list from the list, and the second returns the value of the removed element. * *@param key
     * @return java.lang.Object
     */
    public Object lpop(String key) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForList().leftPop(key);
    }

    /** * returns and pops the last element in the list associated with the specified Key, the header element. If the Key does not exist, return nil. * The RPOP command performs two steps: the first is to remove the element to the right of the list from the list, and the second is to return the value of the element that was removed. * *@param key
     * @return java.lang.Object
     */
    public Object rpop(String key) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForList().rightPop(key);
    }

    /** * The start and end parameters of the command are both 0-based. That is, 0 represents the first element of the list header (leftmost). * Where the value of start can also be negative, -1 will represent the last element in the list, the tail element, -2 the penultimate element, and so on. * When this command fetches elements, the elements at the start and end positions are also fetched. If the value of start is greater than the number of elements in the list, * empty list will be returned. If the value of end is greater than the number of elements, this command gets all the remaining elements in the list from start(inclusive). * Note: Redis lists start with an index of 0. Obviously, LRANGE numbers 0-1 will fetch all the elements in the list. Returns a list of elements in the specified range. * *@param key
     * @param start
     * @param end
     * @return java.util.List<java.lang.Object>
     */
    public List<Object> lrange(String key, long start, long end) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForList().range(key, start, end);
    }

    /** * keeps only elements within the specified range, and all elements outside the specified range are deleted. * 0 indicates the first element of the list, 1 indicates the second element of the list, and so on. * You can also use negative subscripts, -1 for the last element of the list, -2 for the next-to-last element of the list, and so on. * *@param key
     * @param start
     * @param end
     */
    public void ltrim(String key, long start, long end) {
        if (null == key) {
            return;
        }
        redisTemplate.opsForList().trim(key, start, end);
    }

    /** * This command returns the element at the specified position (index) in the list. Index is 0-based, indicating the element at the beginning of the list. * If index is -1, indicating the element at the end. If the Key is associated with something other than a linked list, the command returns an associated error message. If it goes beyond index returns this returns nil. * *@param key
     * @param index
     * @return java.lang.Object
     * @throws* /
    public Object lindex(String key, long index) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForList().index(key, index);
    }

    /** * Returns the number of elements in the linked list associated with the specified Key, or 0 if the Key does not exist. If the type of the Value associated with the Key is not a linked list, the associated exception is thrown. * *@param key
     * @return java.lang.Long
     */
    public Long llen(String key) {

        if (null == key) {
            return 0L;
        }
        return redisTemplate.opsForList().size(key);
    }
    //***************Set Data type *************

    /** * If a member of the argument already exists in the Set, the member will be ignored and the other members will still be inserted as normal. * If the Key does not exist before the command is executed, the command will create a new Set and insert the parameters later. Returns the actual number of inserted members. * *@param key
     * @paramMembers can be a String or an array of strings *@returnJava.lang. Long Number of successful additions */
    public Long sadd(String key, Object... members) {
        if (null == key) {
            return 0L;
        }
        return redisTemplate.opsForSet().add(key, members);

    }

    /** * Returns the number of members in the Set, or 0 if the Key does not exist. * *@param key
     * @return java.lang.Long
     */
    public Long scard(String key) {
        if (null == key) {
            return 0L;
        }
        return redisTemplate.opsForSet().size(key);

    }

    /** * Determines whether the specified member already exists in the Set associated with the Key. Return true if the Key already exists, false if it does not exist, or if the Key itself does not exist. * *@param key
     * @param member
     * @return java.lang.Boolean
     */
    public Boolean sismember(String key, Object member) {
        if (null == key) {
            return false;
        }
        return redisTemplate.opsForSet().isMember(key, member);

    }

    /** * Just like SPOP, it returns a random member of a Set, but does not delete the returned member. * *@param key
     * @return java.lang.String
     */
    public Object srandmember(String key) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForSet().randomMember(key);

    }

    /** * Just like SPOP, it returns a random member of a Set, but does not delete the returned member. * You can also pass the count argument to randomly obtain multiple elements at once, depending on whether the count is positive or negative. * When count is positive, SRANDMEMBER gets a random count of non-repeating elements from the collection. * If the value of count is greater than the number of elements in the collection, SRANDMEMBER returns all elements in the collection. * when the count is negative, SRANDMEMBER randomly from the set for | count | element, if | count | and the elements in the collection, * all elements will return not enough to swallow the repeat element, if the key does not exist, it returns nil. * *@param key
     * @param count
     * @return java.util.List<java.lang.String>
     */
    public List<Object> srandmember(String key, int count) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForSet().randomMembers(key, count);

    }

    /** * randomly removes a value from a set by key and returns the value **@param key
     * @return java.lang.String
     */
    public Object spop(String key) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForSet().pop(key);

    }

    /** * Get all values in the set by key **@param key
     * @return java.util.Set<java.lang.String>
     */
    public Set<Object> smembers(String key) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForSet().members(key);

    }

    /** * Removes the specified member from the Set associated with the Key. Non-existent parameter members are ignored. * If the Key does not exist, it is treated as an empty Set. Returns the actual number of members removed from the Set, or 0 if none. * *@param key
     * @param members
     * @return java.lang.Long
     */
    public Long srem(String key, Object... members) {
        if (null == key) {
            return 0L;
        }
        return redisTemplate.opsForSet().remove(key, members);

    }

    /** * moves the element value from one set to another@param srckey
     * @param dstkey
     * @param member
     * @return java.lang.Long
     * @throws* /
    public Boolean smove(String srckey, String dstkey, Object member) {
        if (null == srckey || null == dstkey) {
            return false;
        }
        return redisTemplate.opsForSet().move(srckey, member, dstkey);

    }


    /** * gets the union of two sets **@param key
     * @param otherKeys
     * @returnJava.util. Set<java.lang.Object> returns the combined value of both collections */
    public Set<Object> sUnion(String key, String otherKeys) {
        if (null == key || otherKeys == null) {
            return null;
        }
        return redisTemplate.opsForSet().union(key, otherKeys);
    }
    **********Sorted Set data type ********************

    /** * add all the members and their scores to the Sorted Set with the given key. * If a member of the argument already exists at the time of addition, this command updates the member's score to the new value and reorders the member based on the new value. * If the key does not exist, this command creates a new Sorted Set Value for the key and inserts the score/member pair into it. * *@param key
     * @param score
     * @param member
     * @return java.lang.Long
     */
    public Boolean zadd(String key, double score, Object member) {
        if (null == key) {
            return false;
        }
        return redisTemplate.opsForZSet().add(key, member, score);

    }


    /** * This command will remove the members specified in the argument. Non-existent members will be ignored. * If the Value associated with the Key is not a Sorted Set, an error message will be returned. The actual number of deleted members is returned if the operation succeeds. * *@param key
     * @paramMembers can be a string or an array of strings *@return java.lang.Long
     */
    public Long zrem(String key, Object... members) {
        if (null == key || null == members) {
            return 0L;
        }
        return redisTemplate.opsForZSet().remove(key, members);

    }

    /** * returns the number of members in the Sorted Set, or 0 if the Key does not exist. * *@param key
     * @return java.lang.Long
     */
    public Long zcard(String key) {
        if (null == key) {
            return 0L;
        }
        return redisTemplate.opsForZSet().size(key);
    }

    /** * this command increments the specified score to the specified member in the specified Key. If the member does not exist, the command will add the member and assume its initial score is 0, * then add increment to its score. If the Key does not exist, the command creates the Sorted Set associated with the Key, *, and contains the specified member whose score is the increment parameter. If the Key is not associated with a Sorted Set type, an error message related to * will be returned. The new fraction represented as a string if no error is reported. * *@param key
     * @param score
     * @param member
     * @return java.lang.Double
     */
    public Double zincrby(String key, double score, Object member) {
        if (null == key) {
            throw new NullPointerException("Key cannot be empty");
        }
        return redisTemplate.opsForZSet().incrementScore(key, member, score);
    }

    /** * This command is used to obtain the number of members with scores between min and Max. * (min=<score< = Max) zcount key (min Max = min<score < Max) * (min=<score< Max) Returns the specified number of returns. * *@param key
     * @param min
     * @param max
     * @return java.lang.Long
     */
    public Long zcount(String key, double min, double max) {
        if (null == key) {
            return 0L;
        }
        return redisTemplate.opsForZSet().count(key, min, max);

    }

    /** * The Sorted Set members are stored in ascending order. This command returns the position of the specified members in the argument, * where 0 represents the first member, which has the lowest score in the Sorted Set. If the member exists, its location index value is returned. Otherwise return nil. * *@param key
     * @param member
     * @return java.lang.Long
     */
    public Long zrank(String key, Object member) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForZSet().rank(key, member);

    }

    /** * Returns the member's score as a string if it exists, or null ** otherwise@param key
     * @param member
     * @return java.lang.Double
     */
    public Double zscore(String key, Object member) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForZSet().score(key, member);
    }

    /** * The start and stop parameters are both 0-based. That is, 0 indicates the first member and -1 indicates the last member. If start is greater than the maximum index in the Sorted * Set, or start > stop, an empty collection is returned. If stop is greater than the maximum index value, * this command returns the last member of the collection from start. If WITHSCORES options with optional parameters in the command, * the command in the returned results will include scores of each member of the values, such as value1, value2, score2 score1... . * *@param key
     * @param min
     * @param max
     * @returnJava.util. Set<java.lang.String> Specifies a list of ordered Set members within an interval. * /
    public Set<Object> zrange(String key, long min, long max) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForZSet().range(key, min, max);

    }

    /** * The function of this command is basically the same as that of ZRANGE. The only difference is that this command fetches the members of a specified position by sorting them in reverse order. * is the order from highest to lowest. If members have the same score, they are sorted in descending dictionary order. * *@param key
     * @param start
     * @param end
     * @return java.util.Set<java.lang.String>
     */
    public Set<Object> zReverseRange(String key, long start, long end) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForZSet().reverseRange(key, start, end);

    }

    /** * This command returns all members whose scores are between min and Max, that is, members satisfying the expression min <= score <= Max, * where the returned members are returned in descending order of their scores, or in lexicographical order of the members if they have the same scores. The optional parameter LIMIT is used to LIMIT the number of returned members. * The optional offset parameter indicates that the return starts with the qualified offset member and returns count members. * Refer to ZRANGE for the meaning of the optional WITHSCORES parameter. * Finally, the rules for min and Max can be found in the ZCOUNT command. * *@param key
     * @param max
     * @param min
     * @return java.util.Set<java.lang.String>
     */
    public Set<Object> zrangebyscore(String key, double min, double max) {
        if (null == key) {
            return null;
        }
        return redisTemplate.opsForZSet().rangeByScore(key, min, max);

    }

    /** * This command has the same functions and parameters as ZRANGEBYSCORE except that the sorting method is based on the highest score to the lowest score. Note that the order of the min and Max arguments in this command is reversed from that in the ZRANGEBYSCORE command. * *@param key
     * @param max
     * @param min
     * @return java.util.Set<java.lang.String>
     */
    public Set<Object> zrevrangeByScore(String key, double min, double max) {
        if (null == key) {
            return null;
        }
        returnredisTemplate.opsForZSet().reverseRangeByScore(key, min, max); }}Copy the code

You can test each method if you’re interested!

Example code -GitHub

Example code -Gitee

Personal blog – Ifknow