RedisTemplate to operate Redis, this article is enough (I)
The difference between StringRedisTemplate and RedisTemplate (II)
A small case of StringRedisTemplate (III)
Article Directory
- 1. Introduction to SpringDataRedis
- 1、Redis
- 2、Jedis
- 3、Spring Data Redis
- 2. API usage in RedisTemplate
- 1. Dependence
- 2. Configuration file
- 3. Direct method of RedisTemplate
- 4. String type related operations
- 1) Add cache (2/3 is a progressive value of 1)
- 2) Set the expiration time (set separately)
- 3) Get the cache value (2/3 is the progressive value of 1)
- 4) Delete key
- 5) Increment in sequence
- 6) Decreasing order
- 5. Hash type related operations
- 1) Add cache (2/3 is a progressive value of 1)
- 2) Set the expiration time (set separately)
- 3) Add a Map collection
- 4) Set the expiration time (set separately)
- 5) Extract all small keys
- 6) Extract all value values
- 7) Extract value according to key
- 8) Get all key-value pair collections
- 9) Delete
- 10) Determine whether the value is contained in the Hash
- 6. Set type related operations
- 1) Add Set cache (values can be one or multiple) (2/3 is a progressive value of 1)
- 2) Set the expiration time (set separately)
- 3) Get all values in Set according to the key
- 4) Query from a set based on the value, whether it exists
- 5) Get the length of the Set cache
- 6) Remove the specified element
- 7) Remove the specified key
- 7. LIST type related operations
- 1) Add cache (2/3 is a progressive value of 1)
- 2) Put List into cache
- 3) Set the expiration time (set separately)
- 4) Get all the contents of List cache (start index, end index)
- 5) Element pops up from the left or from the right
- 6) Query elements based on the index
- 7) Get the length of the List cache
- 8) Modify a piece of data in List according to the index (key, index, value)
- 9) Remove N values as value (key, remove number, value)
- 8. Zset type related operations
- 1) Insert elements into the collection and set the score
- 2) Insert multiple elements into the set and set the score
- 3) Print elements in the specified interval according to the ranking order (from small to large), -1 is to print all
- 4) Obtain the score of the specified element
- 5) Return the number of members in the collection
- 6) Return the number of members in the specified score range in the set (Double type)
- 7) Return the ranking of elements in the set within the specified score range (from small to large)
- 8) With offset and number, (key, starting fraction, maximum fraction, offset, number)
- 9) Return the ranking of elements in the set and the score (from small to large)
- 10) Return the ranking of the specified member
- 11) Delete the specified element from the collection
- 12) Delete elements of the specified index range (Long type)
- 13) Delete elements within the specified score range (Double type)
- 14) Add points to the specified element (Double type)
1. Introduction to SpringDataRedis
1、Redis
redis is an open source Key-Value database that runs in memory and is written in C. 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, providing many interfaces for Java language call. You can download it on the official website of Redis. Of course, there are some clients provided by open source enthusiasts, such as Jredis, SRP, etc., and it is recommended to use Jedis.
3、Spring Data Redis
Spring-data-redis is part of the spring family. It provides access to the redis service through simple configuration in srping applications. It highly encapsulates the reids underlying development package (Jedis, JRedis, and RJC). RedisTemplate provides various redis operations, exception handling and serialization, supports publishing and subscriptions, and implements spring 3.1 cache.
spring-data-redis provides the following functions for jedis:
- Connection pool management automatically provides a highly encapsulated "RedisTemplate" class
- Classified and encapsulated a large number of APIs in the Jedis client, encapsulating 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 type
- ListOperations: Data operations for list type
- Provides a convenient operation API for "bound" (binding) for keys. You can encapsulate the specified key through 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:In the POJO object access scenario, the JDK itself serialization mechanism is used to serialize the pojo class through ObjectInputStream/ObjectOutputStream, and finally the byte sequence will be stored in the redis-server. It is the most commonly used serialization strategy at present.
StringRedisSerializer:A scene where the Key or value is a string, encodes the byte sequence of data into a string according to the specified charset, which is a direct encapsulation of "new String(bytes, charset)" and "(charset)". It is the lightest and most efficient strategy.
JacksonJsonRedisSerializer:The jackson-json tool provides the ability to convert between javabean and json. It can serialize pojo instances into json format and store them in Redis, or convert data in json format 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 support for jackson-mapper-asl tool】
2. API usage in RedisTemplate
1. Dependence
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. Configuration file
# Redis Server Connection Port
spring.redis.port=6379
# Redis Server Address
spring.redis.host=127.0.0.1
# Redis database index (default is 0)
spring.redis.database=0
# Redis server connection password (default is empty)
spring.redis.password=
# Maximum number of connections in the connection pool (using negative values means there is no limit)
spring.redis.jedis.pool.max-active=8
# Maximum blocking waiting time for connection pools (using negative values means there is no limit)
spring.redis.jedis.pool.max-wait=-1ms
# Maximum free connection in the connection pool
spring.redis.jedis.pool.max-idle=8
# Minimum idle connection in the connection pool
spring.redis.jedis.pool.min-idle=0
# Connection timeout (milliseconds)
spring.redis.timeout=5000ms
3. Direct method of RedisTemplate
First use @Autowired to inject RedisTemplate (it will be used directly later, so there is no special explanation)
@Autowired
private RedisTemplate redisTemplate;
1. Delete a single key
// Delete key
public void delete(String key){
redisTemplate.delete(key);
}
2. Delete multiple keys
// Delete multiple keys
public void deleteKey (String ...keys){
redisTemplate.delete(keys);
}
3. Specify the expiration time of the key
// Specify the expiration time of the key
public void expire(String key,long time){
redisTemplate.expire(key,time,TimeUnit.MINUTES);
}
4. Obtain expiration time according to key
// Get expiration time according to key
public long getExpire(String key){
Long expire = redisTemplate.getExpire(key);
return expire;
}
5. Determine whether the key exists
// Determine whether the key exists
public boolean hasKey(String key){
return redisTemplate.hasKey(key);
}
4. String type related operations
1) Add cache (2/3 is a progressive value of 1)
//1. Set the value through redisTemplate
redisTemplate.boundValueOps("StringKey").set("StringValue");
redisTemplate.boundValueOps("StringKey").set("StringValue",1, TimeUnit.MINUTES);
//2. Set the value through BoundValueOperations
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
stringKey.set("StringVaule");
stringKey.set("StringValue",1, TimeUnit.MINUTES);
//3. Set the value through ValueOperations
ValueOperations ops = redisTemplate.opsForValue();
ops.set("StringKey", "StringVaule");
ops.set("StringValue","StringVaule",1, TimeUnit.MINUTES);
2) Set the expiration time (set separately)
redisTemplate.boundValueOps("StringKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("StringKey",1,TimeUnit.MINUTES);
3) Get the cache value (2/3 is the progressive value of 1)
//1. Set the value through redisTemplate
String str1 = (String) redisTemplate.boundValueOps("StringKey").get();
//2. Get the value through BoundValueOperations
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
String str2 = (String) stringKey.get();
//3. Get the value through ValueOperations
ValueOperations ops = redisTemplate.opsForValue();
String str3 = (String) ops.get("StringKey");
4) Delete key
Boolean result = redisTemplate.delete("StringKey");
5) Increment in sequence
redisTemplate.boundValueOps("StringKey").increment(3L);
6) Decreasing order
redisTemplate.boundValueOps("StringKey").increment(-3L);
5. Hash type related operations
1) Add cache (2/3 is a progressive value of 1)
//1. Set the value through redisTemplate
redisTemplate.boundHashOps("HashKey").put("SmallKey", "HashVaue");
//2. Set the value through BoundValueOperations
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
hashKey.put("SmallKey", "HashVaue");
//3. Set the value through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
hashOps.put("HashKey", "SmallKey", "HashVaue");
2) Set the expiration time (set separately)
redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);
3) Add a Map collection
HashMap<String, String> hashMap = new HashMap<>();
redisTemplate.boundHashOps("HashKey").putAll(hashMap );
4) Set the expiration time (set separately)
redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);
5) Extract all small keys
//1. Get the value through redisTemplate
Set keys1 = redisTemplate.boundHashOps("HashKey").keys();
//2. Get the value through BoundValueOperations
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
Set keys2 = hashKey.keys();
//3. Get the value through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
Set keys3 = hashOps.keys("HashKey");
6) Extract all value values
//1. Get the value through redisTemplate
List values1 = redisTemplate.boundHashOps("HashKey").values();
//2. Get the value through BoundValueOperations
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
List values2 = hashKey.values();
//3. Get the value through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
List values3 = hashOps.values("HashKey");
7) Extract value according to key
//1. Obtain through redisTemplate
String value1 = (String) redisTemplate.boundHashOps("HashKey").get("SmallKey");
//2. Get the value through BoundValueOperations
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
String value2 = (String) hashKey.get("SmallKey");
//3. Get the value through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
String value3 = (String) hashOps.get("HashKey", "SmallKey");
8) Get all key-value pair collections
//1. Obtain through redisTemplate
Map entries = redisTemplate.boundHashOps("HashKey").entries();
//2. Get the value through BoundValueOperations
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
Map entries1 = hashKey.entries();
//3. Get the value through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
Map entries2 = hashOps.entries("HashKey");
9) Delete
//Delete the small key
redisTemplate.boundHashOps("HashKey").delete("SmallKey");
//Delete the big key
redisTemplate.delete("HashKey");
10) Determine whether the value is contained in the Hash
Boolean isEmpty = redisTemplate.boundHashOps("HashKey").hasKey("SmallKey");
6. Set type related operations
1) Add Set cache (values can be one or multiple) (2/3 is a progressive value of 1)
//1. Set the value through redisTemplate
redisTemplate.boundSetOps("setKey").add("setValue1", "setValue2", "setValue3");
//2. Set the value through BoundValueOperations
BoundSetOperations setKey = redisTemplate.boundSetOps("setKey");
setKey.add("setValue1", "setValue2", "setValue3");
//3. Set the value through ValueOperations
SetOperations setOps = redisTemplate.opsForSet();
setOps.add("setKey", "SetValue1", "setValue2", "setValue3");
2) Set the expiration time (set separately)
redisTemplate.boundValueOps("setKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("setKey",1,TimeUnit.MINUTES);
3) Get all values in Set according to the key
//1. Get the value through redisTemplate
Set set1 = redisTemplate.boundSetOps("setKey").members();
//2. Get the value through BoundValueOperations
BoundSetOperations setKey = redisTemplate.boundSetOps("setKey");
Set set2 = setKey.members();
//3. Get the value through ValueOperations
SetOperations setOps = redisTemplate.opsForSet();
Set set3 = setOps.members("setKey");
4) Query from a set based on the value, whether it exists
Boolean isEmpty = redisTemplate.boundSetOps("setKey").isMember("setValue2");
5) Get the length of the Set cache
Long size = redisTemplate.boundSetOps("setKey").size();
6) Remove the specified element
Long result1 = redisTemplate.boundSetOps("setKey").remove("setValue1");
7) Remove the specified key
Boolean result2 = redisTemplate.delete("setKey");
7. LIST type related operations
1) Add cache (2/3 is a progressive value of 1)
//1. Set the value through redisTemplate
redisTemplate.boundListOps("listKey").leftPush("listLeftValue1");
redisTemplate.boundListOps("listKey").rightPush("listRightValue2");
//2. Set the value through BoundValueOperations
BoundListOperations listKey = redisTemplate.boundListOps("listKey");
listKey.leftPush("listLeftValue3");
listKey.rightPush("listRightValue4");
//3. Set the value through ValueOperations
ListOperations opsList = redisTemplate.opsForList();
opsList.leftPush("listKey", "listLeftValue5");
opsList.rightPush("listKey", "listRightValue6");
2) Put List into cache
ArrayList<String> list = new ArrayList<>();
redisTemplate.boundListOps("listKey").rightPushAll(list);
redisTemplate.boundListOps("listKey").leftPushAll(list);
3) Set the expiration time (set separately)
redisTemplate.boundValueOps("listKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("listKey",1,TimeUnit.MINUTES);
4) Get all the contents of List cache (start index, end index)
List listKey1 = redisTemplate.boundListOps("listKey").range(0, 10);
5) Element pops up from the left or from the right
String listKey2 = (String) redisTemplate.boundListOps("listKey").leftPop(); //Popt an element from the left
String listKey3 = (String) redisTemplate.boundListOps("listKey").rightPop(); //Popt an element from the right
6) Query elements based on the index
String listKey4 = (String) redisTemplate.boundListOps("listKey").index(1);
7) Get the length of the List cache
Long size = redisTemplate.boundListOps("listKey").size();
8) Modify a piece of data in List according to the index (key, index, value)
redisTemplate.boundListOps("listKey").set(3L,"listLeftValue3");
9) Remove N values as value (key, remove number, value)
redisTemplate.boundListOps("listKey").remove(3L,"value");
8. Zset type related operations
1) Insert elements into the collection and set the score
//1. Set the value through redisTemplate
redisTemplate.boundZSetOps("zSetKey").add("zSetVaule", 100D);
//2. Set the value through BoundValueOperations
BoundZSetOperations zSetKey = redisTemplate.boundZSetOps("zSetKey");
zSetKey.add("zSetVaule", 100D);
//3. Set the value through ValueOperations
ZSetOperations zSetOps = redisTemplate.opsForZSet();
zSetOps.add("zSetKey", "zSetVaule", 100D);
2) Insert multiple elements into the set and set the score
DefaultTypedTuple<String> p1 = new DefaultTypedTuple<>("zSetVaule1", 2.1D);
DefaultTypedTuple<String> p2 = new DefaultTypedTuple<>("zSetVaule2", 3.3D);
redisTemplate.boundZSetOps("zSetKey").add(new HashSet<>(Arrays.asList(p1,p2)));
3) Print elements in the specified interval according to the ranking order (from small to large), -1 is to print all
Set<String> range = redisTemplate.boundZSetOps("zSetKey").range(0, -1);
4) Obtain the score of the specified element
Double score = redisTemplate.boundZSetOps("zSetKey").score("zSetVaule");
5) Return the number of members in the collection
Long size = redisTemplate.boundZSetOps("zSetKey").size();
6) Return the number of members in the specified score range in the set (Double type)
Long COUNT = redisTemplate.boundZSetOps("zSetKey").count(0D, 2.2D);
7) Return the ranking of elements in the set within the specified score range (from small to large)
Set byScore = redisTemplate.boundZSetOps("zSetKey").rangeByScore(0D, 2.2D);
8) With offset and number, (key, starting fraction, maximum fraction, offset, number)
Set<String> ranking2 = redisTemplate.opsForZSet().rangeByScore("zSetKey", 0D, 2.2D 1, 3);
9) Return the ranking of elements in the set and the score (from small to large)
Set<TypedTuple<String>> tuples = redisTemplate.boundZSetOps("zSetKey").rangeWithScores(0L, 3L);
for (TypedTuple<String> tuple : tuples) {
System.out.println(tuple.getValue() + " : " + tuple.getScore());
}ss
10) Return the ranking of the specified member
//From small to adult
Long startRank = redisTemplate.boundZSetOps("zSetKey").rank("zSetVaule");
//From large to small
Long endRank = redisTemplate.boundZSetOps("zSetKey").reverseRank("zSetVaule");
11) Delete the specified element from the collection
redisTemplate.boundZSetOps("zSetKey").remove("zSetVaule");
12) Delete elements of the specified index range (Long type)
redisTemplate.boundZSetOps("zSetKey").removeRange(0L,3L);
13) Delete elements within the specified score range (Double type)
redisTemplate.boundZSetOps("zSetKey").removeRangeByScorssse(0D,2.2D);
14) Add points to the specified element (Double type)
Double score = redisTemplate.boundZSetOps("zSetKey").incrementScore("zSetVaule",1.1D);