Summary of common RedisTemplate methods (refer to official document 2.6.2)

Posted by jdwmk on Sat, 26 Feb 2022 20:54:42 +0100

1. Introduction

RedisTemplate is the most advanced Abstract client provided by Spring Data Redis to users. Users can directly perform a variety of operations through RedisTemplate.

1.1 class inheritance

public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware {
}
  • RedisAccessor: Base class for RedisTemplate defining common properties. Not intended to be used directly.
    RedisTemplate defines the base class of common properties. It is not intended to be used directly.
  • RedisOperations: Interface that specified a basic set of Redis operations, implemented by RedisTemplate. Not often used but a useful option for extensibility and testability (as it can be easily mocked or stubbed).
    Specify a set of interfaces for basic Redis operations, which are implemented by RedisTemplate. Not often used, but a useful option for scalability and testability (because it can be easily emulated or stub).
  • BeanClassLoaderAware: Callback that allows a bean to be aware of the bean class loader; that is, the class loader used by the present bean factory to load bean classes. This is mainly intended to be implemented by framework classes which have to pick up application classes by name despite themselves potentially being loaded from a shared class loader.
    Allow the bean to know the callback of the bean class loader; That is, the class loader used by the current bean factory to load bean classes. This is mainly implemented by framework classes, which must select application classes by name, although they may be loaded from the shared class loader.

1.2 method

// Configure default serialization and deserialization tool classes
2.afterPropertiesSet
// Perform relevant operation s based on parameters, such as transactions
3.execute
// Perform pipelining pipeline related operations
4.executePipelined
// Perform operations related to the specified connection
5.executeWithStickyConnection
// Execute the execute method in the session
6.executeSession
// Create RedisConnection proxy class
7.createRedisConnectionProxy
// Pretreatment of connection
8.preProcessConnection
// After the result is processed, nothing is done by default
9.postProcessResult
// Whether to expose local connections to RedisCallback
10.isExposeConnection
// Set whether to expose local connections to RedisCallback
11.setExposeConnection
// 12 to 26 are to set and obtain relevant serialization tool classes
12.isEnableDefaultSerializer
13.setEnableDefaultSerializer
14.getDefaultSerializer
15.setDefaultSerializer
16.setKeySerializer
17.getKeySerializer
18.setValueSerializer
19.getValueSerializer
20.getHashKeySerializer
21.setHashKeySerializer
22.getHashValueSerializer
23.setHashValueSerializer
24.getStringSerializer
25.setStringSerializer
26.setScriptExecutor
// 27 to 34 are private methods and are not available for external use
27.rawKey
28.rawString
29.rawValue
30.rawKeys
31.deserializeKey
32.deserializeMixedResults
33.deserializeSet
34.convertTupleValues
// Execute transaction
35.exec
36.execRaw
// Delete operation
37.delete
// Contact link
38.unlink
// Check whether the specified key is included
39.hasKey
40.countExistingKeys
// Set expiration time
41.expire
42.expireAt
// Convert to byte stream and send message to channel
43.convertAndSend
// Get expiration time
44.getExpire
// Returns all key s according to the passed in regular expression
46.keys
// Cancel the expiration time of the specified key
47.persist
// Move the specified key and index to the database
48.move
// Get a key randomly from the key space
49.randomKey
// Change the specified key to the target key
50.rename
// When the key does not exist, change the specified key to the target key
51.renameIfAbsent
// Sets the type stored in the specified key
52.type
// Retrieves the serialized version of the value stored in the key
53.dump
// Execute the restore command of Redis
54.restore
// Mark the beginning of transaction blocking
55.multi
// Discard all commands issued after multi
56.discard
// Observe the modification of the specified key after the start of transaction, i.e. multi
57.watch
// Refresh all previously observed key s
58.unwatch
// Sort key elements
59.sort
// Close client connection
60.killClient
// Relevant information and statistics of the client requesting connection
61.getClientList
// Change the replication configuration to the new master
62.slaveOf
// Change this machine to master
63.slaveOfNoOne
// 64 to 79 are operations to obtain corresponding information
64.opsForCluster
65.opsForGeo
66.boundGeoOps
67.boundHashOps
68.opsForHash
69.opsForHyperLogLog
70.opsForList
71.boundListOps
72.boundSetOps
73.opsForSet
74.opsForStream
75.boundStreamOps
76.boundValueOps
77.opsForValue
78.boundZSetOps
79.opsForZSet
// Set whether transactions are supported
80.setEnableTransactionSupport
// Set the class loader of the bean
81.setBeanClassLoader

1.3 function introduction

Spring data redis provides the following functions:

  1. The connection pool is automatically managed, and a highly encapsulated "RedisTemplate" class is provided

  2. The same type of operation is encapsulated as operation interface

    ValueOperations: simple K-V operation
    SetOperations: set type data operations
    ZSetOperations: zset type data operation
    HashOperations: data operations for map type
    ListOperations: data operations for list type

  3. It provides a "bound" convenient operation API for keys. You can encapsulate the specified key through bound, and then perform a series of operations without specifying the key again "explicitly", that is, BoundKeyOperations

    BoundValueOperations
    BoundSetOperations
    BoundListOperations
    BoundSetOperations
    BoundHashOperations

  4. Encapsulate transaction operations with container control.

  5. For the "serialization / deserialization" of data, a variety of alternative strategies (RedisSerializer) are provided

    1.JdkSerializationRedisSerializer: the access scenario of POJO object. Using JDK's own serialization mechanism, the POJO class is serialized through ObjectInputStream/ObjectOutputStream. Finally, the byte sequence will be stored in redis server. Is currently the most commonly used serialization strategy.
    2.StringRedisSerializer: when the Key or value is a string, encode the byte sequence of the data into a string according to the specified charset, which is the direct encapsulation of "newString(bytes,charset)" and "string.getBytes(charset)". Is the most lightweight and efficient strategy.
    3. jackson jsonredisserializer: jackson json tool provides the conversion ability between JavaBeans and json. It can serialize pojo instances into json format and store them in redis, or convert json format data into pojo instances. Because the jackson tool needs to specify the Class type explicitly when serializing and deserializing, this strategy is slightly complicated to encapsulate.
    4.OxmSerializer: it provides the ability to convert JavaBeans to xml. Currently available three-party support includes jaxb and Apache xmlbeans; The data stored in redis will be xml tools. However, using this strategy, programming will be difficult and inefficient; Not recommended. [spring oxm module support required]

    If your data needs to be parsed by a third-party tool, you should use StringRedisSerializer instead of JdkSerializationRedisSerializer.

2. RedisTemplate top-level method

  1. Determine whether the given key exists. If yes, return true. If not, return false
    redisTemplate.hasKey(K key)
    
  2. Delete the given key
    redisTemplate.delete(K key)
    
  3. Delete the set of the given key
    redisTemplate.delete(Collection<K> keys)
    
  4. Execute the Redis dump command and return the result, and serialize the key value into byte [] type
    redisTemplate.dump(K key)
    
  5. Set the expiration time of the passed in key value and set the expiration time of the given key as the date timestamp
    redisTemplate.expire(K key, long timeout, TimeUnit unit)
    redisTemplate.expireAt(K key, Date date)
    
  6. Find all key s that match the given pattern, and return a Set type with no duplicate
    redisTemplate.keys(K pattern)
    
  7. Rename oldKey to newKey.
    redisTemplate.rename(K oldKey, K newKey)
    
  8. Get the type of key value
    redisTemplate.	type(K key)
    
  9. Rename the key oldKey to newKey only if the newKey does not exist.
    redisTemplate.renameIfAbsent(K oldKey, K newKey)
    
  10. Randomly obtain a key from redis
    redisTemplate.randomKey()
    
  11. Get the remaining expiration time of the current key
    redisTemplate.getExpire(K key)
    
  12. Get the remaining expiration time and set the time unit
    redisTemplate.	getExpire(K key, TimeUnit timeUnit)
    
  13. Delete the expiration time of the key
    redisTemplate.	persist(K key)
    
  14. Move the given index with key to the database
    redisTemplate.	move(K key, int dbIndex)
    

3. RedisTemplate.opsForValue() method

  1. Set the values of key and value
    redisTemplate.opsForValue().set(K key, V value)
    
  2. Get the value of key
    redisTemplate.opsForValue().get(Object key)
    
  3. Set the values of key and value, and set the expiration time at the same time
    redisTemplate.opsForValue().set(K key, V value, Duration timeout)
    
  4. Get substring of key value between start and end
    redisTemplate.opsForValue().get(K key, long start, long end)
    
  5. Set the value of key and return its old value
    redisTemplate.opsForValue().getAndSet(K key, V value)
    
  6. Get multiple key s
    redisTemplate.opsForValue().multiGet(Collection<K> keys)
    
  7. After obtaining the value of the original key, add a new string
    redisTemplate.opsForValue().append(K key, String value)
    
  8. Incrementally increase the double value
    redisTemplate.opsForValue().increment(K key, double increment)
    
  9. Use the increment(K key, long delta) method to store the long value incrementally (positive value will increase automatically, negative value will decrease automatically)
    redisTemplate.opsForValue().increment(K key, long increment)
    
  10. Set multiple keys to multiple values using the key value pairs provided in the collection only if the provided key does not exist.
    redisTemplate.opsForValue().multiSetIfAbsent(Map<? extends K,? extends V> map)
    
  11. Set multiple keys to multiple values using the key value pairs provided in the collection.
    Map map = new HashMap(); map.put("1","1"); map.put("2","2"); 
    map.put("3","3"); 
    redisTemplate.opsForValue().multiSet(Map<? extends K,? extends V> map)
    
  12. Gets the length of the string of the specified key
    redisTemplate.opsForValue().size(K key)
    
  13. Overwrite the part of the key starting from the specified offset with the given value.
    redisTemplate.opsForValue().set(K key, V value, long offset)
    
  14. If the key does not exist, set the key to save the string value. If it exists, return false; otherwise, return true
    redisTemplate.opsForValue().setIfAbsent(key, value)
    
  15. Reset the value of the key and add the expiration time
    redisTemplate.opsForValue().set(key, value, timeout, unit)
    
  16. Change the binary offset bit value to value
    redisTemplate.opsForValue().setBit(K key, long offset, boolean value)
    
  17. For the string value stored by the key, obtain the bit on the specified offset
    redisTemplate.opsForValue().getBit(K key, long offset)
    

4. RedisTemplate.opsForHash() method

  1. Get the value of the given hashKey from the hash at the key, that is, the key field (hashKey) value
    redisTemplate.opsForHash().get(H key, Object hashKey)
    
  2. Get the entire hash stored in the key, that is, get all values
    redisTemplate.opsForHash().entries(H key)
    
  3. Set the value of hash key
    redisTemplate.opsForHash().put(H key, HK hashKey, HV value)
    
  4. Use the data provided in m to set multiple hash fields to multiple values, that is, use map to assign values
    redisTemplate.opsForHash().putAll(H key, Map<? extends HK,? extends HV> m)
    
  5. The value of the hash hashKey is set only when the hashKey does not exist.
    redisTemplate.opsForHash().putIfAbsent(H key, HK hashKey, HV value)
    
  6. Delete the given hash keys
    redisTemplate.opsForHash().delete(H key, Object... hashKeys)
    
  7. Determines whether the given hash key exists
    redisTemplate.opsForHash().hasKey(H key, Object hashKey)
    
  8. Increase the value of hash hashKey by a given increment
    redisTemplate.opsForHash().increment(H key, HK hashKey, double increment)
    redisTemplate.opsForHash().increment(H key, HK hashKey, long increment)
    
  9. Get the hashKey set (field) of the hash at the key
    redisTemplate.opsForHash().keys(H key)
    
  10. Gets the hash size of the key.
    redisTemplate.opsForHash().size(H key)
    
  11. Get the hash value at the key
    redisTemplate.opsForHash().values(H key)
    
  12. View matching key value pairs
    redisTemplate.opsForHash().scan(H key, ScanOptions options)
    

5. RedisTemplate.opsForList() method

  1. Get the value in the list according to the index
    redisTemplate.opsForList().index(key, index)
    
  2. Get all the values from the start index to the end index in the list
    redisTemplate.opsForList().range(key, start, end)
    
  3. Add the value to the top of the list
    redisTemplate.opsForList().leftPush(key, value)
    
  4. Directly add a new list to the old list
    redisTemplate.opsForList().leftPushAll(key, value)
    
  5. Add a new value when the List exists
    redisTemplate.opsForList().leftPushIfPresent(key, value)
    
  6. Prefix the index of the pivot value with a value
    redisTemplate.opsForList().leftPush(key, pivot, value)
    
  7. Add in first in first out order
    redisTemplate.opsForList().rightPush(key,value)redisTemplate.opsForList().rightPushAll(key, value)
    
  8. Add a value after the pivot element
    redisTemplate.opsForList().rightPush(key, pivot, value)
    
  9. Sets the value of the specified index
    redisTemplate.opsForList().set(key, index, value)
    
  10. Removes and gets the first element in the list
    redisTemplate.opsForList().leftPop(key)redisTemplate.opsForList().leftPop(key, timeout, unit)
    
  11. Remove and get the last element of the list
    redisTemplate.opsForList().rightPop(key)redisTemplate.opsForList().rightPop(key, timeout, unit)
    
  12. 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)
    
  13. Delete the element with value equal to value in the set
    redisTemplate.opsForList().remove(key, index, value)
    
  14. Clip List
    redisTemplate.opsForList().trim(key, start, end)
    
  15. Get the size of the list
    redisTemplate.opsForList().size(key)
    

6. RedisTemplate.opsForSet() method

  1. Add element
    redisTemplate.opsForSet().add(key, values)
    
  2. Removing Elements
    redisTemplate.opsForSet().remove(key, values)
    
  3. Delete a random element and return
    redisTemplate.opsForSet().pop(key)
    
  4. Gets the size of the collection
    redisTemplate.opsForSet().size(key)
    
  5. Judge whether the value value exists in the set
    redisTemplate.opsForSet().isMember(key, value)
    
  6. Gets the intersection of two sets and returns a set
    redisTemplate.opsForSet().intersect(key, otherKey)
    
  7. Get the two intersections of the key set and the otherKey set and store them in destKey
    redisTemplate.opsForSet().intersectAndStore(key, otherKey, destKey)
    
  8. The intersection of the key set and multiple sets is stored in the destKey unordered set
    redisTemplate.opsForSet().intersectAndStore(key, otherKeys, destKey)
    
  9. Gets the union of multiple sets
    redisTemplate.opsForSet().union(key, otherKeys)
    
  10. Get the union of multiple sets and store it in destKey
    redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey)
    
  11. Get difference set
    redisTemplate.opsForSet().difference(key, otherKeys)
    
  12. Get the difference set and store it in destKey
    redisTemplate.opsForSet().differenceAndStore(key, otherKey, destKey)
    
  13. Gets an element in the collection at random
    redisTemplate.opsForSet().randomMember(key)
    
  14. Gets all elements in the collection
    redisTemplate.opsForSet().members(key)
    
  15. Randomly get count values in the collection
    redisTemplate.opsForSet().randomMembers(key, count)
    
  16. Randomly obtain count values in the set, but remove the duplicate
    redisTemplate.opsForSet().distinctRandomMembers(key, count)
    
  17. Traversal set
    redisTemplate.opsForSet().scan(key, options)
    

7. RedisTemplate.opsForZSet() method

  1. Add elements, sort from small to large
    redisTemplate.opsForZSet().add(key, value, score)
    
  2. Delete multiple values
    redisTemplate.opsForZSet().remove(key, values)
    
  3. Increase the score value of the element and return the increased value at the same time
    redisTemplate.opsForZSet().incrementScore(key, value, delta)
    
  4. Returns the ranking of elements in the collection from small to large
    redisTemplate.opsForZSet().rank(key, value)
    
  5. Returns the ranking of elements in the collection from large to small
    redisTemplate.opsForZSet().reverseRank(key, value)
    
  6. Gets the element of the specified interval in the collection
    redisTemplate.opsForZSet().reverseRangeWithScores(key, start,end)
    
  7. Query the elements in the collection and sort them from small to large
    redisTemplate.opsForZSet().reverseRangeByScore(key, min, max)
    redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, min, max)
    
  8. Sort from high to low, and then get the value between the minimum and maximum
    redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, start, end)
    
  9. Get the number of elements according to the score value
    redisTemplate.opsForZSet().incrementScore(key, value, delta)
    
  10. Gets the size of the collection
    redisTemplate.opsForZSet().size(key)redisTemplate.opsForZSet().zCard(key)
    
  11. Get the score value of key and value elements in the collection
    redisTemplate.opsForZSet().score(key, value)
    
  12. Removes the specified index element
    redisTemplate.opsForZSet().removeRange(key, start, end)
    
  13. Removes the collection member of the specified score range
    redisTemplate.opsForZSet().removeRangeByScore(key, min, max)
    
  14. Get the union of key and otherKey and store it in destKey
    redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey)
    
  15. Get the intersection of key and otherKey and store it in destKey
    redisTemplate.opsForZSet().intersectAndStore(key, otherKey, destKey)
    

Topics: Java Redis