RedisTemplate details

Keywords: Database Redis Cache

I. overview of RedisTemplate

1.Redis

Redis is an open source key value database, which runs in memory and is written in C language. Redis is usually used for enterprise development 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 official website of Redis. Of course, there are some clients provided by open source enthusiasts, such as Jredis.SRP. Jedis is recommended.

3.Spring Data Redis

Spring data redis is a part of the spring family. It provides access to redis services through simple configuration in srping applications, and highly encapsulates the underlying development packages of reids (Jedis, JRedis, and RJC). RedisTemplate provides various redis operations, exception handling and sequencing, supports publishing and subscription, and implements spring 3.1 cache.

Spring data redis provides the following functions for jedis:

  1. Automatic connection pool management provides a highly encapsulated "RedisTemplate" class

  2. A large number of APIs in jedis client are classified and encapsulated, and 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: in the light of map Type of data operation
    
    ListOperations: in the light of list Type of data operation
    

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 "serialization / deserialization" of data, a variety of selectable strategies (RedisSerializer) are provided

JdkSerializationRedisSerializer: the access scenario of POJO objects. The JDK serialization mechanism is used to serialize POJO classes through ObjectInputStream/ObjectOutputStream. Finally, the byte sequence will be stored in redis server. Is currently the most commonly used serialization strategy.

StringRedisSerializer: in the scenario where the Key or value is a string, encode the byte sequence of the data 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.

jackson jsonredisserializer: the jackson json tool provides the conversion capability 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 explicitly specify the Class type when serializing and deserializing, this strategy is slightly complicated to encapsulate. [jackson mapper ASL tool support required]

II. Use of RedisTemplate

1.pom.xml dependency

<!--springboot-Redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!--Redis-->
<dependency>
       <groupId>org.springframework.data</groupId>
       <artifactId>spring-data-redis</artifactId>
       <version>2.0.6.RELEASE</version>
</dependency>
<!--jedis-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</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 (0 by default)
spring.redis.database=0
# Redis server connection password (blank by default)
spring.redis.password=
# Maximum number of connections in the connection pool (negative value indicates no limit)
spring.redis.jedis.pool.max-active=8
# Maximum blocking wait time of connection pool (negative value indicates no limit)
spring.redis.jedis.pool.max-wait=-1ms
# Maximum free connections in the connection pool
spring.redis.jedis.pool.max-idle=8
# Minimum free connections in connection pool
spring.redis.jedis.pool.min-idle=0
# Connection timeout (MS)
spring.redis.timeout=5000ms

3. Direct method of redistemplate

First, use @ Autowired to inject RedisTemplate (it will be used directly later without special instructions)

@Autowired
private RedisTemplate redisTemplate;

3.1 deleting a single key

// Delete key
redisTemplate.delete("key");

3.2 deleting multiple key s

//Delete multiple key s
String[] arr = {"key1","key2","key3"};
redisTemplate.delete(arr);

3.3 specified key expiration time

//Specifies the expiration time of the key
redisTemplate.expire("key",time,TimeUnit.MINUTES);

3.4 get expiration time according to key

//Get expiration time according to key
Long expire = redisTemplate.getExpire("key");

3.5 determine whether the key exists

//Determine whether the key exists
boolean result = redisTemplate.hasKey("key");

4.String type related operations

4.1 add cache (2 / 3 is the 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);

4.2 set expiration time (set separately)

redisTemplate.boundValueOps("StringKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("StringKey",1,TimeUnit.MINUTES);

4.3 get 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 value through ValueOperations
ValueOperations ops = redisTemplate.opsForValue();
String str3 = (String) ops.get("StringKey");

4.4 delete key

Boolean result = redisTemplate.delete("StringKey");

4.5 sequential increment

redisTemplate.boundValueOps("StringKey").increment(3L);

4.6 sequential decrement

redisTemplate.boundValueOps("StringKey").increment(-3L);

5.Hash type related operations

5.1 add cache (2 / 3 is the 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");

5.2 set expiration time (set separately)

redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);

5.3 add a Map set

HashMap<String, String> hashMap = new HashMap<>();
redisTemplate.boundHashOps("HashKey").putAll(hashMap);

5.4 set expiration time (set separately)

redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);

5.5 extract all small key s

//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 value through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
Set keys3 = hashOps.keys("HashKey");

5.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 value through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
List values3 = hashOps.values("HashKey");

5.7 extract value according to key

//1. Get 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 value through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
String value3 = (String) hashOps.get("HashKey", "SmallKey");

5.8 get all key value pair sets

//1. Get 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 value through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
Map entries2 = hashOps.entries("HashKey");

5.9 deletion

//Delete small key
redisTemplate.boundHashOps("HashKey").delete("SmallKey");
//Delete large key
redisTemplate.delete("HashKey");

5.10 judge whether the Hash contains this value

Boolean isEmpty = redisTemplate.boundHashOps("HashKey").hasKey("SmallKey");

6.Set type related operations

6.1 add Set cache (the value can be one or more) (2 / 3 is the 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");

6.2 set expiration time (set separately)

redisTemplate.boundValueOps("setKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("setKey",1,TimeUnit.MINUTES);

6.3 get all the values in the 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 value through ValueOperations
SetOperations setOps = redisTemplate.opsForSet();
Set set3 = setOps.members("setKey");

6.4 query whether a set exists according to value

Boolean isEmpty = redisTemplate.boundSetOps("setKey"). isMember("setValue2");

6.5 get the length of Set cache

Long size = redisTemplate.boundSetOps("setKey").size();

6.6 remove specified elements

Long result1 = redisTemplate.boundSetOps("setKey").remove("setValue1");

6.7 remove the specified key

Boolean result2 = redisTemplate.delete("setKey");
  1. List type related operations

7.1 add cache (2 / 3 is the 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");

7.2 putting List into cache

ArrayList<String> list = new ArrayList<>();
redisTemplate.boundListOps("listKey").rightPushAll(list);
redisTemplate.boundListOps("listKey").leftPushAll(list);

7.3 set expiration time (set separately)

redisTemplate.boundValueOps("listKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("listKey",1,TimeUnit.MINUTES);

7.4 get all contents of List cache (start index, end index)

List listKey1 = redisTemplate.boundListOps("listKey").range(0, 10); 

7.5 pop up an element from left or right

String listKey2 = (String) redisTemplate.boundListOps("listKey").leftPop();  //Pop up an element from the left
String listKey3 = (String) redisTemplate.boundListOps("listKey").rightPop(); //Pop up an element from the right

7.6 query elements by index

String listKey4 = (String) redisTemplate.boundListOps("listKey").index(1);

7.7 get the length of the List cache

Long size = redisTemplate.boundListOps("listKey").size();

7.8 modify a piece of data (key, index, value) in the List according to the index

redisTemplate.boundListOps("listKey").set(3L,"listLeftValue3");

7.9 remove N values as value(key, number of removed, value)

redisTemplate.boundListOps("listKey").remove(3L,"value");

8. Related operations of Zset type

8.1 insert elements into the set and set scores

//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);

8.2 insert multiple elements into the set and set scores

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

8.3 print the elements in the specified interval according to the ranking order (from small to large), and - 1 is to print all

Set<String> range = redisTemplate.boundZSetOps("zSetKey").range(key, 0, -1);

8.4 obtain the score of the specified element

Double score = redisTemplate.boundZSetOps("zSetKey").score("zSetVaule");

8.5 return the number of members in the collection

Long size = redisTemplate.boundZSetOps("zSetKey").size();

8.6 return the number of members of the specified score range in the collection (Double type)

Long COUNT = redisTemplate.boundZSetOps("zSetKey").count(0D, 2.2D);

8.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.8 band offset and number, (key, starting score, maximum score, offset, number)

Set<String> ranking2 = redisTemplate.opsForZSet().rangeByScore("zSetKey", 0D, 2.2D 1, 3);

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

8.10 return the ranking of specified members

//from small to large
Long startRank = redisTemplate.boundZSetOps("zSetKey").rank("zSetVaule");
//From big to small
Long endRank = redisTemplate.boundZSetOps("zSetKey").reverseRank("zSetVaule");

8.11 delete the specified element from the collection

redisTemplate.boundZSetOps("zSetKey").remove("zSetVaule");

8.12 delete the element of the specified index range (Long type)

redisTemplate.boundZSetOps("zSetKey").removeRange(0L,3L);

8.13 delete elements within the specified score range (Double type)

redisTemplate.boundZSetOps("zSetKey").removeRangeByScorssse(0D,2.2D);

8.14 bonus points for specified elements (Double type)

Double score = redisTemplate.boundZSetOps("zSetKey").incrementScore("zSetVaule",1.1D);

Posted by kdreg on Mon, 25 Oct 2021 17:38:23 -0700