Common Redis operations

Article catalog

1, Introduction to SpringDataRedis

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, etc. 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 serialization, 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: data operations for map type
  • ListOperations: data operations for list type
  1. 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 explicitly specifying the key again, that is, BoundKeyOperations:
  • BoundValueOperations
  • BoundSetOperations
  • BoundListOperations
  • BoundSetOperations
  • BoundHashOperations
  1. Encapsulate transaction operations with container control.
  2. For "serialization / deserialization" of data, a variety of selectable policies (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]

2, API usage in RedisTemplate

1,pom.xml dependency

<!--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 (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;

1. Delete a single key

// Delete key
public void delete(String key){
    redisTemplate.delete(key);
}

2. Delete multiple key s

// Delete multiple key s
public void deleteKey (String ...keys){
    redisTemplate.delete(keys);
}

3. Specifies the expiration time of the key

// Specifies the expiration time of the key
public void expire(String key,long time){
    redisTemplate.expire(key,time,TimeUnit.MINUTES);
}

4. Get 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 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 values through BoundValueOperations
BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
stringKey.set("StringVaule");
stringKey.set("StringValue",1, TimeUnit.MINUTES);

//3. Setting values through ValueOperations
ValueOperations ops = redisTemplate.opsForValue();
ops.set("StringKey", "StringVaule");
ops.set("StringValue","StringVaule",1, TimeUnit.MINUTES);

2) . set 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 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) . delete key
Boolean result = redisTemplate.delete("StringKey");

5) , sequential increment
redisTemplate.boundValueOps("StringKey").increment(3L);

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

5. Hash type related operations

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 values through BoundValueOperations
BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
hashKey.put("SmallKey", "HashVaue");

//3. Setting values through ValueOperations
HashOperations hashOps = redisTemplate.opsForHash();
hashOps.put("HashKey", "SmallKey", "HashVaue");

2) . set 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 expiration time (set separately)
redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);

5) . extract all small key s
//1. Get the value through redisTemplate
Set keys1 = redisTemplate.boundHashOps("HashKey").keys();

//2. Get 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");

6) . extract all value values
//1. Get the value through redisTemplate
List values1 = redisTemplate.boundHashOps("HashKey").values();

//2. Get 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");

7) . extract the value value according to the key
//1. Get through redisTemplate
String value1 = (String) redisTemplate.boundHashOps("HashKey").get("SmallKey");

//2. Get 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");

8) . get all key value pairs
//1. Get through redisTemplate
Map entries = redisTemplate.boundHashOps("HashKey").entries();

//2. Get 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");

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

10) . judge whether the Hash contains this value
Boolean isEmpty = redisTemplate.boundHashOps("HashKey").hasKey("SmallKey");

6. Set type related operations

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 values through BoundValueOperations
BoundSetOperations setKey = redisTemplate.boundSetOps("setKey");
setKey.add("setValue1", "setValue2", "setValue3");

//3. Setting values through ValueOperations
SetOperations setOps = redisTemplate.opsForSet();
setOps.add("setKey", "SetValue1", "setValue2", "setValue3");

2) . set expiration time (set separately)
redisTemplate.boundValueOps("setKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("setKey",1,TimeUnit.MINUTES);

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

4) . query whether a set exists according to value
Boolean isEmpty = redisTemplate.boundSetOps("setKey").isMember("setValue2");

5) , get the length of 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 the progressive value of 1)
//1. Set the value through redisTemplate
redisTemplate.boundListOps("listKey").leftPush("listLeftValue1");
redisTemplate.boundListOps("listKey").rightPush("listRightValue2");

//2. Set values through BoundValueOperations
BoundListOperations listKey = redisTemplate.boundListOps("listKey");
listKey.leftPush("listLeftValue3");
listKey.rightPush("listRightValue4");

//3. Setting values through ValueOperations
ListOperations opsList = redisTemplate.opsForList();
opsList.leftPush("listKey", "listLeftValue5");
opsList.rightPush("listKey", "listRightValue6");

2) . put the List into the cache
ArrayList<String> list = new ArrayList<>();
redisTemplate.boundListOps("listKey").rightPushAll(list);
redisTemplate.boundListOps("listKey").leftPushAll(list);

3) . set expiration time (set separately)
redisTemplate.boundValueOps("listKey").expire(1,TimeUnit.MINUTES);
redisTemplate.expire("listKey",1,TimeUnit.MINUTES);

4) . get all the contents of the List cache (start index, end index)
List listKey1 = redisTemplate.boundListOps("listKey").range(0, 10); 

5) , pop 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

6) Query elements according to 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 (key, index, value) in the List according to the index
redisTemplate.boundListOps("listKey").set(3L,"listLeftValue3");

9) . remove N values as value(key, number of removed, value)
redisTemplate.boundListOps("listKey").remove(3L,"value");

8. Related operations of Zset type

1) , insert elements into the collection and set scores
//1. Set the value through redisTemplate
redisTemplate.boundZSetOps("zSetKey").add("zSetVaule", 100D);

//2. Set values through BoundValueOperations
BoundZSetOperations zSetKey = redisTemplate.boundZSetOps("zSetKey");
zSetKey.add("zSetVaule", 100D);

//3. Setting values through ValueOperations
ZSetOperations zSetOps = redisTemplate.opsForZSet();
zSetOps.add("zSetKey", "zSetVaule", 100D);

2) , insert multiple elements into the collection 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)));

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(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 collection (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 score, maximum score, offset, number)
Set<String> ranking2 = redisTemplate.opsForZSet().rangeByScore("zSetKey", 0D, 2.2D 1, 3);

9) . return the ranking of the elements in the collection 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 members
//from small to large
Long startRank = redisTemplate.boundZSetOps("zSetKey").rank("zSetVaule");
//From big to small
Long endRank = redisTemplate.boundZSetOps("zSetKey").reverseRank("zSetVaule");

11) , delete the specified element from the collection
redisTemplate.boundZSetOps("zSetKey").remove("zSetVaule");

12) , delete the element 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);

The original link, if any infringement, please inform to delete

Keywords: Redis

Added by Ali_baba on Fri, 31 Dec 2021 01:39:31 +0200