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:
-
The connection pool is automatically managed, and a highly encapsulated "RedisTemplate" class is provided
-
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 -
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 -
Encapsulate transaction operations with container control.
-
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
- Determine whether the given key exists. If yes, return true. If not, return false
redisTemplate.hasKey(K key)
- Delete the given key
redisTemplate.delete(K key)
- Delete the set of the given key
redisTemplate.delete(Collection<K> keys)
- Execute the Redis dump command and return the result, and serialize the key value into byte [] type
redisTemplate.dump(K key)
- 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)
- Find all key s that match the given pattern, and return a Set type with no duplicate
redisTemplate.keys(K pattern)
- Rename oldKey to newKey.
redisTemplate.rename(K oldKey, K newKey)
- Get the type of key value
redisTemplate. type(K key)
- Rename the key oldKey to newKey only if the newKey does not exist.
redisTemplate.renameIfAbsent(K oldKey, K newKey)
- Randomly obtain a key from redis
redisTemplate.randomKey()
- Get the remaining expiration time of the current key
redisTemplate.getExpire(K key)
- Get the remaining expiration time and set the time unit
redisTemplate. getExpire(K key, TimeUnit timeUnit)
- Delete the expiration time of the key
redisTemplate. persist(K key)
- Move the given index with key to the database
redisTemplate. move(K key, int dbIndex)
3. RedisTemplate.opsForValue() method
- Set the values of key and value
redisTemplate.opsForValue().set(K key, V value)
- Get the value of key
redisTemplate.opsForValue().get(Object key)
- 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)
- Get substring of key value between start and end
redisTemplate.opsForValue().get(K key, long start, long end)
- Set the value of key and return its old value
redisTemplate.opsForValue().getAndSet(K key, V value)
- Get multiple key s
redisTemplate.opsForValue().multiGet(Collection<K> keys)
- After obtaining the value of the original key, add a new string
redisTemplate.opsForValue().append(K key, String value)
- Incrementally increase the double value
redisTemplate.opsForValue().increment(K key, double increment)
- 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)
- 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)
- 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)
- Gets the length of the string of the specified key
redisTemplate.opsForValue().size(K key)
- Overwrite the part of the key starting from the specified offset with the given value.
redisTemplate.opsForValue().set(K key, V value, long offset)
- 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)
- Reset the value of the key and add the expiration time
redisTemplate.opsForValue().set(key, value, timeout, unit)
- Change the binary offset bit value to value
redisTemplate.opsForValue().setBit(K key, long offset, boolean value)
- 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
- 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)
- Get the entire hash stored in the key, that is, get all values
redisTemplate.opsForHash().entries(H key)
- Set the value of hash key
redisTemplate.opsForHash().put(H key, HK hashKey, HV value)
- 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)
- The value of the hash hashKey is set only when the hashKey does not exist.
redisTemplate.opsForHash().putIfAbsent(H key, HK hashKey, HV value)
- Delete the given hash keys
redisTemplate.opsForHash().delete(H key, Object... hashKeys)
- Determines whether the given hash key exists
redisTemplate.opsForHash().hasKey(H key, Object hashKey)
- 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)
- Get the hashKey set (field) of the hash at the key
redisTemplate.opsForHash().keys(H key)
- Gets the hash size of the key.
redisTemplate.opsForHash().size(H key)
- Get the hash value at the key
redisTemplate.opsForHash().values(H key)
- View matching key value pairs
redisTemplate.opsForHash().scan(H key, ScanOptions options)
5. RedisTemplate.opsForList() method
- Get the value in the list according to the index
redisTemplate.opsForList().index(key, index)
- Get all the values from the start index to the end index in the list
redisTemplate.opsForList().range(key, start, end)
- Add the value to the top of the list
redisTemplate.opsForList().leftPush(key, value)
- Directly add a new list to the old list
redisTemplate.opsForList().leftPushAll(key, value)
- Add a new value when the List exists
redisTemplate.opsForList().leftPushIfPresent(key, value)
- Prefix the index of the pivot value with a value
redisTemplate.opsForList().leftPush(key, pivot, value)
- Add in first in first out order
redisTemplate.opsForList().rightPush(key,value)redisTemplate.opsForList().rightPushAll(key, value)
- Add a value after the pivot element
redisTemplate.opsForList().rightPush(key, pivot, value)
- Sets the value of the specified index
redisTemplate.opsForList().set(key, index, value)
- Removes and gets the first element in the list
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 element with value equal to value in the set
redisTemplate.opsForList().remove(key, index, value)
- Clip List
redisTemplate.opsForList().trim(key, start, end)
- Get the size of the list
redisTemplate.opsForList().size(key)
6. RedisTemplate.opsForSet() method
- Add element
redisTemplate.opsForSet().add(key, values)
- Removing Elements
redisTemplate.opsForSet().remove(key, values)
- Delete a random element and return
redisTemplate.opsForSet().pop(key)
- Gets the size of the collection
redisTemplate.opsForSet().size(key)
- Judge whether the value value exists in the set
redisTemplate.opsForSet().isMember(key, value)
- Gets the intersection of two sets and returns a set
redisTemplate.opsForSet().intersect(key, otherKey)
- Get the two intersections of the key set and the otherKey set and store them in destKey
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)
- Gets the union of multiple sets
redisTemplate.opsForSet().union(key, otherKeys)
- Get the union of multiple sets and store it in destKey
redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey)
- Get difference set
redisTemplate.opsForSet().difference(key, otherKeys)
- Get the difference set and store it in destKey
redisTemplate.opsForSet().differenceAndStore(key, otherKey, destKey)
- Gets an element in the collection at random
redisTemplate.opsForSet().randomMember(key)
- Gets all elements in the collection
redisTemplate.opsForSet().members(key)
- Randomly get count values in the collection
redisTemplate.opsForSet().randomMembers(key, count)
- Randomly obtain count values in the set, but remove the duplicate
redisTemplate.opsForSet().distinctRandomMembers(key, count)
- Traversal set
redisTemplate.opsForSet().scan(key, options)
7. RedisTemplate.opsForZSet() method
- Add elements, sort from small to large
redisTemplate.opsForZSet().add(key, value, score)
- Delete multiple values
redisTemplate.opsForZSet().remove(key, values)
- Increase the score value of the element and return the increased value at the same time
redisTemplate.opsForZSet().incrementScore(key, value, delta)
- Returns the ranking of elements in the collection from small to large
redisTemplate.opsForZSet().rank(key, value)
- Returns the ranking of elements in the collection from large to small
redisTemplate.opsForZSet().reverseRank(key, value)
- Gets the element of the specified interval in the collection
redisTemplate.opsForZSet().reverseRangeWithScores(key, start,end)
- 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)
- Sort from high to low, and then get the value between the minimum and maximum
redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, start, end)
- Get the number of elements according to the score value
redisTemplate.opsForZSet().incrementScore(key, value, delta)
- Gets the size of the collection
redisTemplate.opsForZSet().size(key)redisTemplate.opsForZSet().zCard(key)
- Get the score value of key and value elements in the collection
redisTemplate.opsForZSet().score(key, value)
- Removes the specified index element
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 it in destKey
redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey)
- Get the intersection of key and otherKey and store it in destKey
redisTemplate.opsForZSet().intersectAndStore(key, otherKey, destKey)