Detailed explanation of RedisTemplate method

Keywords: Java Database Redis

maven dependency

<!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <!--<version>2.1.4.RELEASE</version>-->
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>

redis serialization mode configuration

@Configuration
public class RedisConfig {

    /**
     * Set the Redis serialization method. The JDK serializer is used by default, which is inefficient. Here we use FastJsonRedisSerializer
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // key serialization
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // value serialization
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        // Hash key serialization
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash value serialization
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}

1: Redis String data structure
Set the current key and value values

redisTemplate.opsForValue().set(key, value)

redisTemplate.opsForValue().set("num","123");

Set the current key and value values and set the expiration time

redisTemplate.opsForValue().set(key, value, timeout, unit)

redisTemplate.opsForValue().set("num","123",10, TimeUnit.SECONDS);

TimeUnit.DAYS / / days
TimeUnit.HOURS / / hours
TimeUnit.MINUTES / / minutes
TimeUnit.SECONDS / / seconds
TimeUnit.MILLISECONDS / / MS

Set the old key to value and return the old key (set the string value of the key and return its old value)

redisTemplate.opsForValue().getAndSet(key, value);

Add a string to the end based on the original value

redisTemplate.opsForValue().append(key, value)

Gets the length of the string

redisTemplate.opsForValue().size(key)

Reset the value corresponding to the key. If it exists, it returns false; otherwise, it returns true

redisTemplate.opsForValue().setIfAbsent(key, value)

Set map collection to redis

Map valueMap = new HashMap();  
valueMap.put("valueMap1","map1");  
valueMap.put("valueMap2","map2");  
valueMap.put("valueMap3","map3");  
redisTemplate.opsForValue().multiSet(valueMap); 

If the corresponding map collection name does not exist, add it; otherwise, do not modify it

Map valueMap = new HashMap();  
valueMap.put("valueMap1","map1");  
valueMap.put("valueMap2","map2");  
valueMap.put("valueMap3","map3");  
redisTemplate.opsForValue().multiSetIfAbsent(valueMap); 

Use the increment(K key, long delta) method to store the long value in an incremental manner (positive value will increase automatically and negative value will decrease automatically)

redisTemplate.opsForValue().increment(key, increment);

Batch get value

public List<String> multiGet(Collection<String> keys) {
    return redisTemplate.opsForValue().multiGet(keys);
 }

Returns the type of value stored by the incoming key

redisTemplate.type(key);

Modify the name of the key in redis

 public void renameKey(String oldKey, String newKey) {
    redisTemplate.rename(oldKey, newKey);
}

If the old value key exists, change the old value to the new value

public Boolean renameOldKeyIfAbsent(String oldKey, String newKey) {
    return redisTemplate.renameIfAbsent(oldKey, newKey);
}

Judge whether there is a value corresponding to the key. If yes, return true; if not, return false

redisTemplate.hasKey(key)

Delete a single key value

redisTemplate.delete(key)

Batch delete key

redisTemplate.delete(keys) //Where keys: Collection < k > keys

Set expiration time

public Boolean expire(String key, long timeout, TimeUnit unit) {
    return redisTemplate.expire(key, timeout, unit);
 }
 public Boolean expireAt(String key, Date date) {
    return redisTemplate.expireAt(key, date);
  }

Returns the remaining expiration time corresponding to the current key

redisTemplate.getExpire(key);

Returns the remaining expiration time and specifies the time unit

public Long getExpire(String key, TimeUnit unit) {
    return redisTemplate.getExpire(key, unit);
}

Find the matching key value and return a Set collection type

public Set<String> getPatternKey(String pattern) {
    return redisTemplate.keys(pattern);
}

Persist key

public Boolean persistKey(String key) {
    return redisTemplate.persist(key);
}

Move the key of the current database to the specified redis database

public Boolean moveToDbIndex(String key, int dbIndex) {
    return redisTemplate.move(key, dbIndex);
}

2. Hash type
Redis hash is a mapping table of field and value of string type. Hash is especially suitable for storing objects.
Each hash in Redis can store 2 ^ 32 - 1 key value pairs (more than 4 billion).
Gets whether the specified map key in the variable has a value. If the map key exists, the value is obtained. If not, null is returned.

redisTemplate.opsForHash().get(key, field)

Get key value pairs in variables

public Map<Object, Object> hGetAll(String key) {
    return redisTemplate.opsForHash().entries(key);
}

New hashMap value

redisTemplate.opsForHash().put(key, hashKey, value)

Add key value pairs as a map set

public void hPutAll(String key, Map<String, String> maps) {
    redisTemplate.opsForHash().putAll(key, maps);
}

Set only if hashKey does not exist

public Boolean hashPutIfAbsent(String key, String hashKey, String value) {
    return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
}

Delete one or more hash table fields

public Long hashDelete(String key, Object... fields) {
    return redisTemplate.opsForHash().delete(key, fields);
}

Check whether the specified field in the hash table exists

public boolean hashExists(String key, String field) {
    return redisTemplate.opsForHash().hasKey(key, field);
}

Add increment to the integer value of the specified field in the hash table key

public Long hashIncrBy(String key, Object field, long increment) {
    return redisTemplate.opsForHash().increment(key, field, increment);
}
 public Double hIncrByDouble(String key, Object field, double delta) {
    return redisTemplate.opsForHash().increment(key, field, delta);
}

Get all fields in the hash table

redisTemplate.opsForHash().keys(key)

Get all the values that exist in the hash table

public List<Object> hValues(String key) {
    return redisTemplate.opsForHash().values(key);
}

Gets the number of fields in the hash table

redisTemplate.opsForHash().size(key)

Match to get key value pairs. ScanOptions.NONE is to get all key pairs

public Cursor<Entry<Object, Object>> hashScan(String key, ScanOptions options) {
    return redisTemplate.opsForHash().scan(key, options);
}

3. List type
Get elements in the list by index

redisTemplate.opsForList().index(key, index)

Get the elements within the specified range of the list (start position, 0 is the start position, end position, - 1 returns all)

redisTemplate.opsForList().range(key, start, end)

Stored in the header of the list, that is, add one and put it at the front index

redisTemplate.opsForList().leftPush(key, value)

Store multiple values in the List (value can be multiple values or a Collection value)

redisTemplate.opsForList().leftPushAll(key, value)

Add when the List exists

redisTemplate.opsForList().leftPushIfPresent(key, value)

Add in first in first out order (value can be multiple values or Collection var2)

redisTemplate.opsForList().rightPush(key, value)
redisTemplate.opsForList().rightPushAll(key, value)

Sets the value of the element at the specified index

redisTemplate.opsForList().set(key, index, value)

Remove and get the first element in the list (if there is no element in the list, the list will be blocked until the wait times out or a pop-up element is found)

redisTemplate.opsForList().leftPop(key)
redisTemplate.opsForList().leftPop(key, timeout, unit)

Remove and get the last element of the list

redisTemplate.opsForList().rightPop(key)
redisTemplate.opsForList().rightPop(key, timeout, unit)

Pop up an element from the right side of a queue and put it on the leftmost side of another specified queue

redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey)
redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey, timeout, unit)

Delete the elements with value equal to value in the set (index=0, delete all elements with value equal to value; index > 0, delete the first element with value equal to value from the head; index < 0, delete the first element with value equal to value from the tail)

redisTemplate.opsForList().remove(key, index, value)

Clip List

redisTemplate.opsForList().trim(key, start, end)

Gets the List length of the current key

redisTemplate.opsForList().size(key)

4. Set type

Add element

redisTemplate.opsForSet().add(key, values)

Remove element (single value, multiple values)

redisTemplate.opsForSet().remove(key, values)

Gets the size of the collection

redisTemplate.opsForSet().size(key)

Determine whether the set contains value

redisTemplate.opsForSet().isMember(key, value)

Get the intersection of two sets (find the intersection between the unordered set corresponding to key and the unordered set corresponding to otherKey)

redisTemplate.opsForSet().intersect(key, otherKey)

Get the intersection of multiple collections (Collection var2)

redisTemplate.opsForSet().intersect(key, otherKeys)

The intersection of the key set and the otherKey set is stored in the destKey set (where the otherKey can be a single value or a set)

redisTemplate.opsForSet().intersectAndStore(key, otherKey, destKey)

The intersection of the key set and multiple sets is stored in the destKey unordered set

redisTemplate.opsForSet().intersectAndStore(key, otherKeys, destKey)

Get the union of two or more sets (otherKeys can be a single value or a set)

redisTemplate.opsForSet().union(key, otherKeys)

The union of the key set and the otherKey set is stored in destKey (otherKeys can be a single value or a set)

redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey)

Get the difference set of two or more sets (otherKeys can be a single value or a set)

redisTemplate.opsForSet().difference(key, otherKeys)

The difference set is stored in destKey (otherKeys can be a single value or a set)

redisTemplate.opsForSet().differenceAndStore(key, otherKey, destKey)

Gets all elements in the collection

redisTemplate.opsForSet().members(key)

Randomly get count elements in the collection

redisTemplate.opsForSet().randomMembers(key, count)

Gets an element in the collection at random

redisTemplate.opsForSet().randomMember(key)

Traversing a set is similar to an interleaver (scanoptions. None shows all)

redisTemplate.opsForSet().scan(key, options)

5. zSet type

ZSetOperations provides a series of methods to operate on ordered collections

Add elements (the ordered collection is arranged according to the score value of the elements from small to large)

redisTemplate.opsForZSet().add(key, value, score)

Delete the corresponding value. Value can be multiple values

redisTemplate.opsForZSet().remove(key, values)

Increase the score value of the element and return the increased value

redisTemplate.opsForZSet().incrementScore(key, value, delta)

Returns the ranking of elements in the set. The ordered set is arranged from small to large according to the score value of elements

redisTemplate.opsForZSet().rank(key, value)

Returns the ranking of elements in the collection, sorted by the score value of elements from large to small

redisTemplate.opsForZSet().reverseRank(key, value)

Get the elements of the given interval in the collection (start position, end position, - 1 query all)

redisTemplate.opsForZSet().reverseRangeWithScores(key, start,end)

Query the elements in the collection according to the Score value, and the results are sorted from small to large

redisTemplate.opsForZSet().reverseRangeByScore(key, min, max)

Gets the elements with scores between the minimum and maximum from the high to low sort set

redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, start, end)

Get the number of collection elements according to the score value

redisTemplate.opsForZSet().count(key, min, max)

Gets the size of the collection

redisTemplate.opsForZSet().size(key)

Get the score value corresponding to the key and value elements in the collection

redisTemplate.opsForZSet().score(key, value)

Removes the member at the specified index location

redisTemplate.opsForZSet().removeRange(key, start, end)

Removes the collection member of the specified score range

redisTemplate.opsForZSet().removeRangeByScore(key, min, max)

Get the union of key and otherKey and store them in destKey (where otherKeys can be a single string or a collection of strings)

redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey)

Get the intersection of key and otherKey and store it in destKey (where otherKeys can be a single string or a collection of strings)

redisTemplate.opsForZSet().intersectAndStore(key, otherKey, destKey)

Traversal set (as like as two peas) iterator

Cursor<TypedTuple<Object>> scan = opsForZSet.scan("test3", ScanOptions.NONE);
while (scan.hasNext()){
ZSetOperations.TypedTuple<Object> item = scan.next();
System.out.println(item.getValue() + ":" + item.getScore());
}

What is the difference between StringRedisTemplate and RedisTemplate?

  1. The relationship between the two is that StringRedisTemplate inherits RedisTemplate.

  2. The data of the two are not common; That is, StringRedisTemplate can only manage the data in StringRedisTemplate, and RedisTemplate can only manage the data in RedisTemplate.

3. Different serialization methods:

RedisTemplate uses JdkSerializationRedisSerializer to store data, which will be serialized into byte arrays and then stored in Redis database.

StringRedisTemplate uses StringRedisSerializer

When the sequence class used by RedisTemplate operates data, for example, storing data will sequence the data into a byte array, and then store it in the Redis database. When you open Redis to view at this time, you will see that your data is displayed in a byte array instead of in a readable form, similar to the following

Tool class

package com.dw.study.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

/**
 * @Author
 * @ClassName RedisUtils
 * @Description
 * @Date 2021/1/20 12:22
 * @Version 1.0
 */
@Component
public class RedisUtils {

    private final static Logger log = LoggerFactory.getLogger(RedisUtils.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


// ##########################[operation String type]#####################################################

    /**
     * Set cache
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Set the value and set the expiration time in seconds
     *
     * @param key
     * @param value
     * @param time  Expiration time
     * @return
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Set the value of an existing key and return the old value
     *
     * @param key
     * @param value
     * @return
     */
    public Object getAndSet(String key, Object value) {
        try {
            Object andSet = redisTemplate.opsForValue().getAndSet(key, value);
            return andSet;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * If it does not exist, set the value value and return true. Otherwise, false is returned
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setIfAbsent(String key, String value) {
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, value);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Batch setting K - > V to redis
     *
     * @param valueMap
     * @return
     */
    public boolean multiSet(HashMap valueMap) {
        try {
            redisTemplate.opsForValue().multiSet(valueMap);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * If there is no corresponding Map, set K - > V to redis in batch
     *
     * @param valueMap
     * @return
     */
    public boolean multiSetIfAbsent(HashMap valueMap) {
        try {
            redisTemplate.opsForValue().multiSetIfAbsent(valueMap);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }


    /**
     * Add a string to the end based on the original value
     *
     * @param key
     * @param value
     * @return
     */
    public boolean append(String key, String value) {
        try {
            redisTemplate.opsForValue().append(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }


    /**
     * Get value
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * Batch get value
     *
     * @param keys
     * @return
     */
    public List<Object> multiGet(Collection<String> keys) {
        if (CollectionUtils.isEmpty(keys)) {
            return null;
        }
        return redisTemplate.opsForValue().multiGet(keys);
    }


    /**
     * Delete cache, support batch deletion
     *
     * @param key
     */
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(Arrays.asList(key));
            }
        }
    }

    /**
     * Determine whether the key exists
     *
     * @param key key
     * @return true Exists false does not exist
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Get the expiration time of the key according to the key
     *
     * @param key Key cannot be null
     * @return Time (seconds) returns - 1, which means it is permanently valid
     */
    public long getKeyExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * Specify cache expiration time
     *
     * @param key  key
     * @param time Time (seconds)
     * @return
     */
    public boolean expireKey(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Use the increment(K key, long increment) method to store the long value incrementally (positive value will increase automatically, negative value will decrease automatically)
     *
     * @param key
     * @param increment
     * @return
     */
    public void increment(String key, long increment) {
        redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     * Use the increment(K key, double increment) method to store the double value in an incremental manner (positive value increases automatically, negative value decreases automatically)
     *
     * @param key
     * @param increment
     * @return
     */
    public void increment(String key, double increment) {
        redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     * Modify the name of the key in redis
     *
     * @param oldKey
     * @param newKey
     */
    public void renameKey(String oldKey, String newKey) {
        redisTemplate.rename(oldKey, newKey);
    }

    /**
     * If the old value key exists, change the old value to the new value
     *
     * @param oldKey
     * @param newKey
     * @return
     */
    public Boolean renameOldKeyIfAbsent(String oldKey, String newKey) {
        return redisTemplate.renameIfAbsent(oldKey, newKey);
    }

    // ##########################[operation Hash type]#####################################################

    /**
     * Batch add key value pairs in Map
     *
     * @param mapName map name
     * @param maps
     */
    public boolean hashPutAll(String mapName, Map<String, String> maps) {
        try {
            redisTemplate.opsForHash().putAll(mapName, maps);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }


    /**
     * Add a key value pair
     *
     * @param mapName
     * @param key
     * @param value
     */
    public boolean hashPutOne(String mapName, String key, String value) {
        try {
            redisTemplate.opsForHash().put(mapName, key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Add a key value pair, which is set only when the hashKey does not exist
     *
     * @param mapName
     * @param hashKey
     * @param value
     */
    public boolean hashPutOneIfAbsent(String mapName, String hashKey, String value) {
        try {
            redisTemplate.opsForHash().putIfAbsent(mapName, hashKey, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Get all key value pairs in mapName
     *
     * @param mapName Map name
     * @return
     */
    public Object hashGetOne(String mapName, Object hashKey) {
        return redisTemplate.opsForHash().get(mapName, hashKey);
    }

    /**
     * Get all key value pairs in mapName
     *
     * @param mapName Map name
     * @return
     */
    public Map<Object, Object> hashGetAll(String mapName) {
        return redisTemplate.opsForHash().entries(mapName);
    }


    /**
     * Delete one or more hash table fields
     *
     * @param key
     * @param fields
     * @return
     */
    public Long hashDelete(String key, Object... fields) {
        return redisTemplate.opsForHash().delete(key, fields);
    }

    /**
     * Check whether the specified field in the hash table exists
     *
     * @param key
     * @param field
     * @return
     */
    public boolean hashExists(String key, String field) {
        return redisTemplate.opsForHash().hasKey(key, field);
    }

    /**
     * Add increment to the integer value of the specified field in the hash table key
     *
     * @param key
     * @param field
     * @param increment
     * @return
     */
    public Long hashIncrementByLong(String key, Object field, long increment) {
        return redisTemplate.opsForHash().increment(key, field, increment);
    }

    /**
     * Add increment to the double of the specified field in the hash table key
     *
     * @param key
     * @param field
     * @param delta
     * @return
     */
    public Double hashIncrementByDouble(String key, Object field, double delta) {
        return redisTemplate.opsForHash().increment(key, field, delta);
    }

    /**
     * Get all the key s in the hash table
     *
     * @param mapName map name
     * @return
     */
    public Set<Object> hashKeys(String mapName) {
        return redisTemplate.opsForHash().keys(mapName);
    }

    /**
     * Get all the values that exist in the hash table
     *
     * @param mapName map name
     * @return
     */
    public List<Object> hashValues(String mapName) {
        return redisTemplate.opsForHash().values(mapName);
    }

    /**
     * Gets the size of the hash table
     *
     * @param mapName
     * @return
     */
    public Long hashSize(String mapName) {
        return redisTemplate.opsForHash().size(mapName);
    }

    // ##########################[operation List type]#####################################################

    /**
     * Sets the value to the header in the List
     *
     * @param key
     * @param value
     * @return
     */
    public Boolean listAddInHead(String key, Object value) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Batch set values to the header in the List
     *
     * @param key    List name
     * @param values
     * @return
     */
    public Boolean listAddAllInHead(String key, Collection<Object> values) {
        try {
            redisTemplate.opsForList().leftPushAll(key, values);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * If List - > key exists, set the value to the header in the List
     *
     * @param key   List name
     * @param value
     * @return
     */
    public Boolean listAddIfPresent(String key, Object value) {
        try {
            redisTemplate.opsForList().leftPushIfPresent(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Sets the value to the end of the List
     *
     * @param key   List name
     * @param value
     * @return
     */
    public Boolean listAddInEnd(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Batch set values to the end of the List
     *
     * @param key    List name
     * @param values
     * @return
     */
    public Boolean listAddAllInEnd(String key, Collection<Object> values) {
        try {
            redisTemplate.opsForList().rightPushAll(key, values);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Set the value in list - > key through index
     *
     * @param key
     * @param index
     * @param value
     * @return
     */
    public Boolean listAddByIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }


    /**
     * Get the value in the list according to the index
     *
     * @param key   list name
     * @param index
     * @return
     */
    public Object listGetByIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    /**
     * Get the value in the list according to the index range
     *
     * @param key   list name
     * @param start
     * @param end
     * @return
     */
    public List<Object> listGetByRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * Remove and get the first element in the list (if there is no element in the list, the list will be blocked until the wait times out or a pop-up element is found)
     *
     * @param key list name
     * @return
     */
    public Object listLeftPop(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    /**
     * Remove and get the last element in the list (if there is no element in the list, the list will be blocked until the wait times out or a pop-up element is found)
     *
     * @param key list name
     * @return
     */
    public Object listRightPop(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }

    /**
     * Delete an element with a value equal to value in the collection(
     * index=0, Delete all elements with value equal to value;
     * index>0, Delete the first element with value equal to value from the header;
     * index<0, Delete the first element with value equal to value from the tail)
     *
     * @param key
     * @param index
     * @param value
     * @return
     */
    public Long listRemove(String key, long index, Object value) {
        Long removeNum = redisTemplate.opsForList().remove(key, index, value);
        return removeNum;
    }

// ##########################[operation type]#####################################################

    /**
     * Set value to set set (batch supported)
     *
     * @param key
     * @param value
     * @return
     */
    public Boolean setAdd(String key, Object... value) {
        try {
            redisTemplate.opsForSet().add(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * Remove the value from the Set set, and batch operation is supported
     *
     * @param key
     * @param values
     * @return Number of removed
     */
    public long setRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    /**
     * Judge whether value exists in the Set
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setIsExist(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    // ##########################[operating latitude and longitude]#####################################################

    /***
     * Add the specified geospatial location (latitude, longitude, name) to the specified key.
     * @param key redis key of
     * @param longitude   longitude
     * @param latitude   latitude
     * @param name  The name (identification) of the coordinate
     * @return
     */
    public Long geoAdd(String key, double longitude, double latitude, String name) {
//        Long addedNum = redisTemplate.opsForGeo().add("city", new Point(116.405285, 39.904989), "Beijing");
        Long addedNum = redisTemplate.opsForGeo().add(key, new Point(longitude, latitude), name);
        return addedNum;
    }

    /***
     * Return the positions (longitude and latitude) of all the given positioning elements from the key.
     * @param key redis key of
     * @param nameList A collection of coordinate names (identifiers)
     */
    public List<Point> geoGet(String key, List<String> nameList) {
        List<Point> points = redisTemplate.opsForGeo().position(key, nameList);
        return points;
    }


    /***
     * [Get distance between two coordinates]
     * According to the distance between the two coordinates named name1 and name2 in the key name in redis
     * @param key redis key of
     * @param name1 Coordinate name (identification) 1
     * @param name2 Coordinate name (identification) 2
     * @return distance(Unit (m)
     */
    public double geoGetDistance(String key, String name1, String name2) {
        double distance = redisTemplate.opsForGeo()
                .distance(key, name1, name2, RedisGeoCommands.DistanceUnit.METERS).getValue();
        return distance;
    }


    /***
     * [Get coordinates within the specified range]
     * Draw a circle around the given latitude and longitude, and return to the position element contained in the key,
     * All position elements whose distance from the center does not exceed the given maximum distance, and the average distance between all position elements and the center is given.
     * @param key redis key of
     * @param longitude   longitude
     * @param latitude   latitude
     * @param distance Distance in meters
     * @param count If count > 0, count coordinates are returned at most; otherwise, all coordinates are returned
     * @return
     */
    public GeoResults<RedisGeoCommands.GeoLocation<Object>> geoGetCoordinatesWithinRange(String key,
                                                                                         double longitude,
                                                                                         double latitude,
                                                                                         Integer distance,
                                                                                         Integer count) {
        //Draw a circle centered on the current coordinate to identify the range of distance covered by the current coordinate, point (longitude, latitude) distance (distance quantity, distance unit)
        Circle circle = new Circle(new Point(longitude, latitude), new Distance(distance, RedisGeoCommands.DistanceUnit.METERS));
        // The information obtained from redis includes: the distance from the center coordinate, the current coordinate, and sorted in ascending order. If count > 0, only count coordinates will be taken, otherwise all coordinates will be returned
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
                .newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending();
        if (count > 0) {
            args.limit(count);
        }
        GeoResults<RedisGeoCommands.GeoLocation<Object>> radius = redisTemplate.opsForGeo().radius(key, circle, args);
        return radius;
    }

    /***
     * [Get coordinates within the specified range]
     * Draw a circle around the coordinate name (identification) name in the given key and return to the position element contained in the key,
     * All position elements whose distance from the center does not exceed the given maximum distance, and the average distance between all position elements and the center is given.
     * @param key redis key of
     * @param name Coordinate name (identification)
     * @param distance distance
     * @param count If count > 0, count coordinates are returned at most; otherwise, all coordinates are returned
     * @return
     */
    public GeoResults<RedisGeoCommands.GeoLocation<Object>> geoGetCoordinatesWithinRange(String key,
                                                                           String name,
                                                                           Integer distance,
                                                                           Integer count) {
        // Create a distance object
        Distance distances = new Distance(distance, RedisGeoCommands.DistanceUnit.METERS);
        // Parameters to be obtained from redis
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
                .newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending();
        if (count > 0) {
            args.limit(count);
        }
        GeoResults<RedisGeoCommands.GeoLocation<Object>> radius = redisTemplate.opsForGeo()
                .radius(key, name, distances, args);
        return radius;
    }


}

Posted by ITEagle03 on Thu, 04 Nov 2021 14:41:41 -0700