当前位置:网站首页>[redistemplate method details]

[redistemplate method details]

2022-06-12 07:43:00 Conquer!

maven rely on

<!--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 configuration

@Configuration
public class RedisConfig {

    /**
     *  Set up Redis Serialization mode , Default JDKSerializer How to serialize , Low efficiency , Here we use  FastJsonRedisSerializer
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // key serialize 
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // value serialize 
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        // Hash key serialize 
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash value serialize 
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}

1:Redis Of String data structure
Set current key as well as value value

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

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

Set current key as well as value Value and set the expiration time

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

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

TimeUnit.DAYS // God
TimeUnit.HOURS // Hours
TimeUnit.MINUTES // minute
TimeUnit.SECONDS // second
TimeUnit.MILLISECONDS // millisecond

Put the old key Set to value, And return to the old key( Set up key String value And return its old value )

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

Add a new string to the end based on the original value

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

Gets the length of the string

redisTemplate.opsForValue().size(key)

To reset key Corresponding value , If there is a return false, Otherwise return to true

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

Set up map Assemble 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, otherwise do not modify

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

adopt increment(K key, long delta) Method to store... Incrementally long value ( A positive value increases itself , Negative values are self decreasing )

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

Batch fetch value

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

Return to incoming key The type of value stored

redisTemplate.type(key);

modify redis in key The name of

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

If the old value key In existence , Change old value to new value

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

To determine if there is key The corresponding value , With the return true, No return false

redisTemplate.hasKey(key)

Removing a single key value

redisTemplate.delete(key)

Batch deletion key

redisTemplate.delete(keys) // among 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 current key The corresponding remaining expiration time

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 a match key value , Return to one Set Collection types

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

take key Persistent save

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

Will be the current database of key Move to specified redis In the database

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

2、Hash type
Redis hash It's a string Type of field and value Mapping table ,hash Ideal for storing objects .
Redis Each of them hash Can be stored 2^32 - 1 Key value pair (40 More than ).
Gets the specified value in the variable map Does the key have a value , If the map Key to get the value , No return null.

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

Get the key value pair in the variable

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

newly added hashMap value

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

With map Add key value pairs in the form of sets

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

Only when the hashKey Set when it doesn't exist

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

Delete one or more hash Table field

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

see hash Whether the specified field in the table exists

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

To the hash table key The integer value of the specified field in plus the increment increment

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 hash Fields in the table

redisTemplate.opsForHash().keys(key)

obtain hash All values present in the table

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

obtain hash The number of fields in the table

redisTemplate.opsForHash().size(key)

Match to get key value pairs ,ScanOptions.NONE 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 the elements in the list by index

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

Get the elements in the specified range of the list (start Starting position , 0 It's the starting position ,end End position , -1 Back to all )

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

Stored in list The head of , That is, add one and put it at the front index

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

Store multiple values in List in (value It can be multiple values , It can also be a Collection value)

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

List Add when you exist

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

Add... In first in first out order (value It can be multiple values , Or is it 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 are no elements in the list, it will block the list until the wait timeout or pop-up elements are 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)

The value in the delete set is equal to value The elements of (index=0, Delete all values equal to value The elements of ; index>0, Delete the first value from the header equal to value The elements of ; index<0, Delete from the tail. The first value is equal to value The elements of )

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

take List Trim the list

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

Get current key Of List List length

redisTemplate.opsForList().size(key)

4、Set type

Additive elements

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

Remove elements ( Single value 、 Multiple values )

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

Get 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 (key The corresponding unordered set and otherKey Find the intersection of the corresponding unordered set )

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

Get the intersection of multiple sets (Collection var2)

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

key Assemble with otherKey The intersection of sets is stored in destKey Collection ( among otherKey It can be a single value or a collection )

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

key The intersection of a set and multiple sets is stored in destKey In an unordered set

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

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

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

key Assemble with otherKey The union of sets is stored in destKey in (otherKeys It can be a single value or a collection )

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

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

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

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

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

Get all the elements in the collection

redisTemplate.opsForSet().members(key)

Random acquisition in the set count Elements

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

Randomly get an element in the set

redisTemplate.opsForSet().randomMember(key)

Traverse set Be similar to Interator(ScanOptions.NONE To display all )

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

5、zSet type

ZSetOperations Provides a series of methods to operate on ordered sets

Additive elements ( The ordered set is based on the elements score Values are arranged from small to large )

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

Delete corresponding value,value Can be multiple values

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

Add element score value , And return the increased value

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

Returns the ranking of elements in the collection , The ordered set is based on the elements score The values are arranged from small to large

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

Returns the ranking of elements in the collection , By element score The values are arranged from large to small

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

Gets the element of the given interval in the set (start Starting position ,end End position , -1 Query all )

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

according to Score Value queries the elements in the collection , The results are sorted from small to large

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

Get the elements with scores between the minimum and maximum from the high to low sorting set

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

according to score Value to get the number of collection elements

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

Get the size of the collection

redisTemplate.opsForZSet().size(key)

Get... In the collection key、value Element corresponding score value

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

Removes the member at the specified index location

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

Remove the specified score Collection members of the scope

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

obtain key and otherKey Union of and stored in destKey in ( among otherKeys It can be a single string or a collection of strings )

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

obtain key and otherKey And stored in destKey in ( among otherKeys It can be a single string or a collection of strings )

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

Ergodic set ( and iterator As like as two peas )

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

StringRedisTemplate and RedisTemplate difference ?

  1. The relationship between the two is StringRedisTemplate Inherit RedisTemplate.

  2. The data of the two are different ; in other words StringRedisTemplate Can only manage StringRedisTemplate The data in it ,RedisTemplate Can only manage RedisTemplate Data in .

3、 Serialization is different :

RedisTemplate It uses JdkSerializationRedisSerializer The stored data will be sequenced into byte array and then stored Redis database .

StringRedisTemplate It uses StringRedisSerializer

RedisTemplate The sequence class used in the operation of data , For example, storing data will first serialize the data into a byte array and then store it in Redis database , Open at this time Redis When checking , You'll see that your data isn't presented in readable form , It's shown as an array of bytes , It's like this

 Insert picture description here

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 the 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 ( Unit second )
     *
     * @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;
        }
    }

    /**
     *  A setting already exists key Value , 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, return true.  Otherwise return to false
     *
     * @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 settings  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, Then set in batch  k->v  To  redis
     *
     * @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 new 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;
        }
    }


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

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


    /**
     *  Delete cache , Batch deletion is supported 
     *
     * @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));
            }
        }
    }

    /**
     *  Judge key Whether there is 
     *
     * @param key  key 
     * @return true  There is  false non-existent 
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     *  according to key  obtain key The expiration time of 
     *
     * @param key  key   Not for null
     * @return  Time ( second )  return -1,  Stands for permanent validity 
     */
    public long getKeyExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     *  Specify cache expiration time 
     *
     * @param key   key 
     * @param time  Time ( second )
     * @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;
        }
    }

    /**
     *  adopt increment(K key, long increment) Method to store... Incrementally long value ( A positive value increases itself , Negative values are self decreasing )
     *
     * @param key
     * @param increment
     * @return
     */
    public void increment(String key, long increment) {
        redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     *  adopt increment(K key, double increment) Method to store... Incrementally double value ( A positive value increases itself , Negative values are self decreasing )
     *
     * @param key
     * @param increment
     * @return
     */
    public void increment(String key, double increment) {
        redisTemplate.opsForValue().increment(key, increment);
    }

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

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

    // ##########################【 operation Hash type 】#####################################################

    /**
     *  Batch addition Map Key value pairs in 
     *
     * @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 , Only when the hashKey Set when it doesn't 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;
        }
    }

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

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


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

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

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

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

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

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

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

    // ##########################【 operation List type 】#####################################################

    /**
     *  Set value to List The head in 
     *
     * @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;
        }
    }

    /**
     *  Set the value in batch to List The head in 
     *
     * @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 there is List->key,  Set the value to List The head in 
     *
     * @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;
        }
    }

    /**
     *  Set value to List The tail of the middle 
     *
     * @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;
        }
    }

    /**
     *  Set the value in batch to List The tail of the middle 
     *
     * @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 by index List->key The value in 
     *
     * @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... According to the index list The value in 
     *
     * @param key   list name 
     * @param index
     * @return
     */
    public Object listGetByIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    /**
     *  Get according to the index range list The value in 
     *
     * @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 are no elements in the list, it will block the list until the wait timeout or pop-up elements are 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 are no elements in the list, it will block the list until the wait timeout or pop-up elements are found )
     *
     * @param key list name 
     * @return
     */
    public Object listRightPop(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }

    /**
     *  The value in the delete set is equal to value The elements of (
     * index=0,  Delete all values equal to value The elements of ;
     * index>0,  Delete the first value from the header equal to value The elements of ;
     * index<0,  Delete from the tail. The first value is equal to value The elements of )
     *
     * @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 Set type 】#####################################################

    /**
     *  Set value to Set aggregate ( Support batch )
     *
     * @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 Set Values in the set , Support batch 
     *
     * @param key
     * @param values
     * @return  Quantity removed 
     */
    public long setRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    /**
     *  Judge Set Whether there is value
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setIsExist(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    // ##########################【 Operating latitude and longitude 】#####################################################

    /***
     *  Geospatial location to be specified ( latitude 、 longitude 、 name ) Add to specified key in .
     * @param key redis Of key
     * @param longitude    longitude 
     * @param latitude    latitude 
     * @param name   The name of the coordinate ( identification )
     * @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;
    }

    /***
     *  from key Returns the location of all the positioning elements ( Longitude and latitude ).
     * @param key redis Of key
     * @param nameList  Coordinate name ( identification ) Set 
     */
    public List<Point> geoGet(String key, List<String> nameList) {
        List<Point> points = redisTemplate.opsForGeo().position(key, nameList);
        return points;
    }


    /***
     * 【 Get the distance between two coordinates 】
     *  according to redis Middle key name (key) in , The name is  name1  and  name2  The distance between two coordinates 
     * @param key redis Of key
     * @param name1  Coordinate name ( identification )1
     * @param name2  Coordinate name ( identification )2
     * @return distance( Unit meter )
     */
    public double geoGetDistance(String key, String name1, String name2) {
        double distance = redisTemplate.opsForGeo()
                .distance(key, name1, name2, RedisGeoCommands.DistanceUnit.METERS).getValue();
        return distance;
    }


    /***
     * 【 Get the coordinates within the specified range 】
     *  Draw a circle around a given latitude and longitude ,  Return key (key) Among the location elements included ,
     *  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 Of key
     * @param longitude    longitude 
     * @param latitude    latitude 
     * @param distance  distance ( Company : rice )
     * @param count  If  count > 0  At most count A coordinate ,  Otherwise return to all 
     * @return
     */
    public GeoResults<RedisGeoCommands.GeoLocation<Object>> geoGetCoordinatesWithinRange(String key,
                                                                                         double longitude,
                                                                                         double latitude,
                                                                                         Integer distance,
                                                                                         Integer count) {
        // Draw a circle centered on the current coordinates , Identify the... Covered by the current coordinates distance The scope of the , Point( longitude ,  latitude ) Distance( Distance ,  Distance units )
        Circle circle = new Circle(new Point(longitude, latitude), new Distance(distance, RedisGeoCommands.DistanceUnit.METERS));
        //  from redis The information obtained contains : The distance from the central coordinate 、 The current coordinates 、 And sort in ascending order , If count > 0  Only count A coordinate , Otherwise return to all 
        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 the coordinates within the specified range 】
     *  With the given key (key) Coordinate names in ( identification )name Draw a circle for the center ,  Return key contains position elements ,
     *  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 Of key
     * @param name  Coordinate name ( identification )
     * @param distance  distance 
     * @param count  If  count > 0  At most count A coordinate ,  Otherwise return to all 
     * @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);
        //  Need from redis Parameters obtained 
        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;
    }


}

 

原网站

版权声明
本文为[Conquer!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120735330982.html

随机推荐