Preface: Introduction to the common methods of RedisTemplate. According to RedisTemplate, some commonly used native operation RedisUtil tool classes of Redis are encapsulated.
1. Introduction to Spring Data Redis
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
1,Redis
redis is an open-source Key-Value database that runs in memory and is written in C language. Enterprise development usually uses Redis to implement caching. Similar products include memcache, memcached, etc.
2,Jedis
Jedis is a Java-oriented client officially launched by Redis, which provides many interfaces for Java language calls. It can be downloaded from the Redis official website. Of course, there are also some clients provided by open source enthusiasts, such as Jredis, SRP, etc. Jedis is recommended.
3,Spring Data Redis
Spring-data-redis is part of the spring family. It provides access to redis services through simple configuration in srping applications. It highly encapsulates the underlying development kits of reids (Jedis, JRedis, and RJC). RedisTemplate provides various redis Operation, exception handling and serialization, support publish subscription, and implement spring 3.1 cache.
spring-data-redis provides the following functions for jedis:
Automatic connection pool management, providing a highly encapsulated "RedisTemplate" class
Classify and encapsulate a large number of APIs in the jedis client, and encapsulate the same type of operation as an operation interface
-
ValueOperations: simple K-V operation
-
SetOperations: set type data operation
-
ZSetOperations: zset type data operation
-
HashOperations: Data operations for map types
-
ListOperations: Data operations for list types
Provides a "bound" (binding) convenient operation API for the key. You can encapsulate the specified key through the bound, and then perform a series of operations without "explicitly" specifying the Key again, that is, BoundKeyOperations:
-
BoundValueOperations
-
BoundSetOperations
-
BoundListOperations
-
BoundSetOperations
-
BoundHashOperations
Encapsulate transaction operations and have container control.
For the "serialization/deserialization" of data, a variety of optional strategies are provided (RedisSerializer)
-
JdkSerializationRedisSerializer: The access scene of POJO objects, using JDK's own serialization mechanism, serializes pojo classes through ObjectInputStream/ObjectOutputStream, and finally redis-server will store byte sequences. It is currently the most commonly used serialization strategy.
-
StringRedisSerializer: In scenarios where the Key or value is a string, the byte sequence of the data is encoded into a string according to the specified charset, which is a direct encapsulation of "new String(bytes, charset)" and "string.getBytes(charset)". is the most lightweight and efficient strategy.
-
JacksonJsonRedisSerializer: The jackson-json tool provides conversion capabilities between javabean s and json. It can serialize pojo instances into json format and store them in redis, and can also convert json format data into pojo instances. Because the jackson tool needs to explicitly specify the Class type when serializing and deserializing, this strategy is slightly more complicated to encapsulate. [Requires jackson-mapper-asl tool support]
2. Common methods of RedisTemplate
Redis commonly used data types: String, Hash, List, Set, zSet
2.1, String type
ValueOperations opsForValue = redisTemplate.opsForValue();
opsForValue.set(key, value); //Set the current key and value opsForValue.set(key, value, offset);//Overwrites the string value stored at the given key with the value parameter, starting at offset offset opsForValue.set(key, value, timeout, unit); //Set the current key and value and set the expiration time opsForValue.setBit(key, offset, value); //Change the binary offset bit value to value opsForValue.setIfAbsent(key, value);//Reset the value corresponding to the key, if it exists, return false, otherwise return true opsForValue.get(key, start, end); //Returns the subcharacters of the string at key opsForValue.getAndSet(key, value); //Set the old key as value and return the old key opsForValue.multiGet(keys); //Get values in batches opsForValue.size(key); //Get the length of the string opsForValue.append(key, value); //Add a string to the end based on the original value opsForValue.increment(key,double increment);//Incrementally stores a double value in a variable opsForValue.increment(key,long increment); //Use the increment(K key, long delta) method to store long values incrementally (positive values are self-incrementing, negative values are self-decreasing) Map valueMap = new HashMap(); valueMap.put("valueMap1","map1"); valueMap.put("valueMap2","map2"); valueMap.put("valueMap3","map3"); opsForValue.multiSetIfAbsent(valueMap); //If the corresponding map collection name does not exist, add it otherwise do not modify opsForValue.multiSet(valueMap); //Set the map collection to redis
2.2, Hash type
HashOperations opsForHash = redisTemplate.opsForHash();
opsForHash.get(key, field); //Get whether the specified map key in the variable has a value, if the map key exists, get the value, if not, return null opsForHash.entries(key); //Get the key-value pair in the variable opsForHash.put(key, hashKey, value); //Add hashMap value opsForHash.putAll(key, maps); //Add key-value pairs in the form of a map collection opsForHash.putIfAbsent(key, hashKey, value); //Only set if hashKey does not exist opsForHash.delete(key, fields); //Delete one or more hash table fields opsForHash.hasKey(key, field); //Check whether the specified field exists in the hash table opsForHash.increment(key, field, long increment); //Add increment to the integer value of the specified field in the hash table key opsForHash.increment(key, field, double increment); //Add increment to the integer value of the specified field in the hash table key opsForHash.keys(key); //Get all the fields in the hash table opsForHash.values(key); //Get all the values existing in the hash table opsForHash.scan(key, options); //Match to get key-value pairs, ScanOptions.NONE to get all key pairs
2.3, List type
ListOperations opsForList = redisTemplate.opsForList();
opsForList.index(key, index); //Get an element in a list by index opsForList.range(key, start, end); //Get the elements within the specified range of the list (start start position, 0 is the start position, end end position, -1 returns all) opsForList.leftPush(key, value); //Stored at the head of the list, that is, add one and put it at the front index opsForList.leftPush(key, pivot, value); //If the value at the pivot exists, add it in front of the pivot opsForList.leftPushAll(key, value); //Store multiple values in the List (value can be multiple values or a Collection value) opsForList.leftPushIfPresent(key, value); //Join when the List exists opsForList.rightPush(key, value); //Add in first-in first-out order (value can be multiple values, or Collection var2) opsForList.rightPushAll(key, value); //Add the value to the right of the pivot element opsForList.set(key, index, value); //Sets the value of the element at the specified index opsForList.trim(key, start, end); //Trim the List list opsForList.size(key); //Get the length of the List list of the current key //Remove and get the first element in the list (if the list has no elements, the list will be blocked until the wait times out or a pop-up element is found) opsForList.leftPop(key); opsForList.leftPop(key, timeout, unit); //Remove and get the last element of the list opsForList.rightPop(key); opsForList.rightPop(key, timeout, unit); //Pops an element from the right side of one queue and puts the element into the leftmost side of another specified queue opsForList.rightPopAndLeftPush(sourceKey, destinationKey); opsForList.rightPopAndLeftPush(sourceKey, destinationKey, timeout, unit); //Delete elements whose value is equal to value in the collection (index=0, delete all elements whose value is equal to value; index>0, delete the first element whose value is equal to value from the head; index<0, delete the first element from the end elements whose value is equal to value) opsForList.remove(key, index, value);
2.4 ,Set type
opsForSet.add(key, values); //add element opsForSet.remove(key, values); //Remove elements (single value, multiple values) opsForSet.pop(key); //remove and return a random element opsForSet.size(key); //Get the size of the collection opsForSet.isMember(key, value); //Determine whether the collection contains value opsForSet.intersect(key, otherKey); //Get the intersection of two sets (the unordered set corresponding to key and the unordered set corresponding to otherKey seek the intersection) opsForSet.intersect(key, otherKeys);//Get the intersection of multiple collections (Collection var2) opsForSet.intersectAndStore(key, otherKey, destKey); //The intersection of the key set and the otherKey set is stored in the destKey set (where otherKey can be a single value or a set) opsForSet.intersectAndStore(key, otherKeys, destKey); //The intersection of the key set and multiple sets is stored in the destKey unordered set opsForSet.union(key, otherKeys); //Get the union of two or more collections (otherKeys can be a single value or a collection) opsForSet.unionAndStore(key, otherKey, destKey); //The union of the key collection and the otherKey collection is stored in destKey (otherKeys can be a single value or a collection) opsForSet.difference(key, otherKeys); //Get the difference of two or more collections (otherKeys can be a single value or a collection) opsForSet.differenceAndStore(key, otherKey, destKey); //The difference is stored in destKey (otherKeys can be a single value or a collection) opsForSet.randomMember(key); //Randomly get an element from a collection opsForSet.members(key); //Get all elements in the collection opsForSet.randomMembers(key, count); //Randomly get count elements in the collection opsForSet.distinctRandomMembers(key, count); //Get the elements in the unordered collection of multiple key s (remove duplicates), count represents the number opsForSet.scan(key, options); //Traversing set is similar to Interator(ScanOptions.NONE is to display all)
2.5, zSet type
ZSetOperations provides a series of methods to operate on ordered collections
ZSetOperations opsForZSet = redisTemplate.opsForZSet();
opsForZSet.add(key, value, score); //Add elements (ordered collections are arranged according to the score value of the elements from small to large) opsForZSet.remove(key, values); //Delete the corresponding value,value can be multiple values opsForZSet.incrementScore(key, value, delta); //Increase the score value of the element and return the increased value opsForZSet.rank(key, value); //Returns the rank of the elements in the collection, the ordered collection is arranged from small to large according to the score value of the elements opsForZSet.reverseRank(key, value); //Returns the rank of the elements in the collection, sorted by the score value of the elements from large to small opsForZSet.reverseRangeWithScores(key, start,end); //Get the elements of the given interval in the collection (start start position, end end position, -1 query all) opsForZSet.reverseRangeByScore(key, min, max); //Query the elements in the collection according to the Score value, and the results are sorted from small to large opsForZSet.reverseRangeByScoreWithScores(key, min, max); //The return value is: Set<ZSetOperations.TypedTuple<V>> opsForZSet.count(key, min, max); //Get the number of collection elements according to the score value opsForZSet.size(key); //Get the size of the collection opsForZSet.zCard(key); //Get the size of the collection opsForZSet.score(key, value); //Get the score value corresponding to the key and value elements in the collection opsForZSet.removeRange(key, start, end); //removes the member at the specified index position opsForZSet.removeRangeByScore(key, min, max); //Remove the set members of the specified score range opsForZSet.unionAndStore(key, otherKey, destKey);//Get the union of key and otherKey and store it in destKey (where otherKeys can be a single string or a collection of strings) opsForZSet.intersectAndStore(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)
3. RedisUtil tool class encapsulation
Some commonly used native operations of Redis are encapsulated according to RedisTemplate
package com.hs.util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Redis Tools */ @Component public class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; /****************** common start ****************/ /** * Specify cache expiration time * @param key key * @param time time (seconds) * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Get the expiration time according to the key * @param key key cannot be null * @return Time (seconds) Return 0 means it is permanently valid */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 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) { e.printStackTrace(); return false; } } /** * delete cache * @param key Can pass a value or multiple */ @SuppressWarnings("unchecked") public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key)); } } } /****************** common end ****************/ /****************** String start ****************/ /** * normal cache fetch * @param key key * @return value */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * normal cache * @param key key * @param value value * @return true success false failure */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Normal cache put and set time * @param key key * @param value value * @param time Time (seconds) time must be greater than 0, if time is less than or equal to 0, it will be set indefinitely * @return true success false failure */ 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) { e.printStackTrace(); return false; } } /** * increment * @param key key * @param delta How much to increase (greater than 0) * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("Increment factor must be greater than 0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * decrease * @param key key * @param delta How much to reduce (less than 0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("The decrement factor must be greater than 0"); } return redisTemplate.opsForValue().increment(key, -delta); } /****************** String end ****************/ /****************** Map start ****************/ /** * HashGet * @param key key cannot be null * @param item item cannot be null * @return value */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * Get all key values corresponding to hashKey * @param key key * @return Corresponding multiple key values */ public Map<Object, Object> hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * @param key key * @param map Corresponding to multiple key values * @return true success false failure */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet and set the time * @param key key * @param map Corresponding to multiple key values * @param time time (seconds) * @return true success false failure */ public boolean hmset(String key, Map<String, Object> map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put data into a hash table, if it does not exist, it will be created * @param key key * @param item item * @param value value * @return true success false failure */ public boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put data into a hash table, if it does not exist, it will be created * @param key key * @param item item * @param value value * @param time Time (seconds) Note: If the existing hash table has time, the original time will be replaced here * @return true success false failure */ public boolean hset(String key, String item, Object value, long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time > 0) { expire(key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Delete the value in the hash table * @param key key cannot be null * @param item item can be multiple cannot be null */ public void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * Determine whether there is a value for this item in the hash table * @param key key cannot be null * @param item item cannot be null * @return true exists false does not exist */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash Increment If it does not exist, one will be created and the newly added value will be returned * @param key key * @param item item * @param by How much to increase (greater than 0) * @return */ public double hincr(String key, String item, long by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash decrease * @param key key * @param item item * @param by To reduce the record (less than 0) * @return */ public double hdecr(String key, String item, long by) { return redisTemplate.opsForHash().increment(key, item, -by); } /****************** Map end ****************/ /****************** Set start ****************/ /** * Get all the values in the Set according to the key * @param key key * @return */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Query from a set according to value, whether it exists * @param key key * @param value value * @return true exists false does not exist */ public boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put data into set cache * @param key key * @param values value can be multiple * @return Number of successes */ public long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * Put the set data into the cache * @param key key * @param time time (seconds) * @param values value can be multiple * @return Number of successes */ public long sSetAndTime(String key, long time, Object... values) { try { Long count = redisTemplate.opsForSet().add(key, values); if (time > 0) expire(key, time); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * Get the length of the set cache * @param key key * @return */ public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * remove value * @param key key * @param values value can be multiple * @return Removed */ public long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /****************** Set end ****************/ /****************** List start ****************/ /** * Get the content of the list cache * @param key key * @param start start * @param end End 0 to -1 for all values * @return */ public List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Get the length of the list cache * @param key key * @return */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * Get the value in the list by index * @param key key * @param index When index index>=0, 0 is the header, 1 is the second element, and so on; when index<0, -1 is the end of the table, -2 is the second-to-last element, and so on * @return */ public Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Put the list into the cache * @param key key * @param value value * @return */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put the list into the cache * @param key key * @param value value * @param time time (seconds) * @return */ public boolean lSet(String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put the list into the cache * @param key key * @param value value * @return */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Put the list into the cache * @param key key * @param value value * @param time time (seconds) * @return */ public boolean lSet(String key, List<Object> value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) expire(key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Modify a piece of data in the list according to the index * @param key key * @param index index * @param value value * @return */ public boolean lUpdateIndex(String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * Remove N values as value * @param key key * @param count how many to remove * @param value value * @return Removed */ public long lRemove(String key, long count, Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } /****************** List end ****************/ }
Reference link:
RedisTemplate operates Redis, this article is enough (1)_ha_lydms' Blog-CSDN Blog_redistemplate