2021-04-16-Redis summary

Posted by cdpapoulias on Fri, 04 Mar 2022 07:11:24 +0100

Redis five data types

String (String)

  • be careful:
    The value of string is not limited to strings, such as ordinary strings, complex strings such as JSON,XML, numbers and even binary, but it can not exceed 512MB

    Next, let's demonstrate the basic operations of adding, deleting, modifying and querying
    SET key value
    GET key
    DEL key
    MSET key1 value1 key2 value2... keyN valueN -- set one or more key value pairs at the same time
    MGET KEY1 KEY2... KEYN – returns the values of all (one or more) given keys

    Flushdb: empty

Hash

  • In Redis, hash type refers to that the key value itself is a key value pair structure.

    We still focus on addition, deletion and modification:
    hSet key filed value
    Hget key field
    GetKey -- get all properties in getKey
    Hdel key field

List

  • The list type in Redis is used to store multiple ordered strings and can be repeated. The bottom layer is a two-way linked list
    Add, delete, modify and check
    LPUSH key value [value...], add elements to the left
    LRANGE key start stop, query list element 0 - 1 indicates all elements of the query list
    RPUSH key value [value...], add elements to the right
    LPOP key, pop up the element on the left
    RPOP key, pop up the element on the right
    LREM KEY_NAME COUNT VALUE: remove the elements in the list equal to the parameter VALUE according to the VALUE of the parameter COUNT

    Other commands:
    LLEN key, length of query list
    LINDEX key index, get the value of the specified index get(int index)
    LSET key index value to set the value of the specified index

Set

  • The collection in Redis is also used to store multiple string elements. The difference is that the collection is not allowed to have duplicate elements, and the elements in the collection are out of order. The bottom layer is a hash table

    Common commands: set
    Sadd key element [element] add element
    Scar key calculates the number of elements
    Smembers key get all elements
    Srem key element [element] delete element
    Sismember key element determines whether an element exists in the set, and returns 1; otherwise, it returns 0
    Pop key randomly pops up elements from the collection

Ordered set (ZSet)

  • The ordered set in Redis is a special set. Firstly, it does not allow duplicate elements in the set. Secondly, it is ordered. However, the implementation of this order is different from the list we mentioned earlier. It is sorted based on scores.

    zset
    Common commands:
    Zadd key score member [score member...] add members and set scores for each member
    Zrange key 0 -1

    Application scenario:
    Ranking system

Five data types of Spring operation

  • After integrating Redis, Spring provides a class for each type to operate Redis.
@Test
public void testOpration() {

   // 1. Operation string
   ValueOperations valueOperations = redisTemplate.opsForValue();
   valueOperations.set("name","admin");
   System.out.println("character string:"+valueOperations.get("name"));

   // 2. Operation hash
   HashOperations hashOperations = redisTemplate.opsForHash();
   Map<String,Object> stuMap = new HashMap<String, Object>();
   stuMap.put("name","Zhang San");
   stuMap.put("age",10);
   hashOperations.putAll("student",stuMap); // Storing objects with hash
   System.out.println(hashOperations.get("student","age"));

   // 3. Operation linked list
   ListOperations listOperations = redisTemplate.opsForList();
   listOperations.leftPushAll("books","Java","Spring","MyBatis");
   List books = listOperations.range("books", 0, -1);
   System.out.println(books);

   // 4. Operation unordered collection
   SetOperations setOperations = redisTemplate.opsForSet();
   setOperations.add("emails","zs@qf.com","ls@qf.com","ww@qf.com");
   System.out.println(setOperations.members("emails"));

   // 5. Orderly collection of operations
   ZSetOperations zSetOperations = redisTemplate.opsForZSet();
   zSetOperations.add("score","zs",10);
   zSetOperations.add("score","ls",20);
   zSetOperations.add("score","ww",15);
   System.out.println(zSetOperations.range("score",0,-1));
}

transaction management

Redis Transaction Features

  • redis transaction is a combination of multi exec commands, which can provide two important guarantees:
    1. A transaction is an isolated operation. The methods in the transaction will be serialized by redis and executed in sequence. The transaction will not be interrupted by commands issued by other clients during execution.

    2. A transaction is an atomic operation that either executes all or does not execute all.
    Redis commands between multi and exec commands will take the form of entering the queue. Until the exec command appears, the queued commands will be sent for execution at one time.

Commands for basic transactions

  • Multi: when the transaction is started, the subsequent commands will enter the queue instead of being executed immediately
    Exec: commit the transaction. If the monitored key has not been modified, the commit command will be used. Otherwise, the rollback command will be executed
    Discard: rollback transaction
    watch key1 [key2]...: listen for some keys. When the monitored key is modified before committing the transaction, the transaction will be rolled back (based on the optimistic lock mechanism)
    unwatch: cancel listening

Basic transaction operations


In Redis, executing a command with wrong format will cause the transaction to fail to commit.

Optimistic locking mechanism

  • A transaction sets listening to a certain attribute and operates on this attribute after the transaction is started. If other transactions modify this attribute during this period, the last transaction fails to execute.

Spring boot operation Redis transaction

@Test
public void testRedisTransaction(){
   try{
      // 1. Start transaction
      redisTemplate.multi();

      // 2. redis operation
      redisTemplate.opsForValue().set("name","admin");
      redisTemplate.opsForValue().set("age",12);

      // 3. Transaction submission
      redisTemplate.exec();
   }catch (Exception e){
      // 4. Abnormal transaction rollback
      redisTemplate.discard();
      e.printStackTrace();
   }
}
  • The following exceptions will appear after the program is executed:

    The exception message says that the transaction is not started when the transaction is rolled back, that is, the transaction is not started and rolled back in a redis connection. The solution is as follows:

@Test
public void testRedisTransaction2(){

   redisTemplate.execute(new SessionCallback() {
      @Nullable // The identification parameter can be empty
      @Override
      public Object execute(RedisOperations redisOperations) throws DataAccessException {
         try{
            // 1. Start transaction
            redisTemplate.multi();

            // 2. redis operation
            redisTemplate.opsForValue().set("name","admin");
            redisTemplate.opsForValue().set("age",12);

            // 3. Transaction submission
            List list = redisTemplate.exec();
            System.out.println(list);
         }catch (Exception e){
            // 4. Abnormal transaction rollback
            redisTemplate.discard();
            e.printStackTrace();
         }
         return null;
      }
   });
  • If you operate Redis with the execute method, you can ensure that all operations in the anonymous class use the same Redis connection object.

pipelined

  • In reality, the reading and writing speed of redis is very fast, and the bottleneck of the system is often the delay in network communication. Redis may be idle for many times and wait for the command to arrive. To solve this problem, you can use redis's pipeline, which is a communication protocol similar to a queue executing a group of commands in batch.
  • Compare with a performance test:
    1. No pipeline technology is used

    2. Use pipeline writing

Topics: Java Redis Back-end queue string