Introduction to Redis

summary

https://baike.baidu.com/item/Redis/6549233?fr=aladdin Baidu Encyclopedia

Basic knowledge

  1. redis has 16 databases by default, and the 0 database is used by default. You can use the * * select * * command to switch

    Connected.
    my:0>select  3    # Switch database
    "OK"
    my:3>dbsize       # View DB size
    "0"
    my:3>
    
  2. Other commands

    my:3>set name "zhang"  # Store data
    "OK"
    my:3>get name        # get data
    "zhang"
    my:3>keys *        #Get all key s
     1)  "name"
    my:3>flushdb       # Empty the current database 
    "OK"
    my:3>flushall     # Empty all databases 
    "OK"
    
  3. redis is single threaded

    Officials say that redis is based on memory, and the CPU is not the performance bottleneck of redis. The bottleneck of redis depends on the bandwidth of the network and the memory of the machine, so single thread is used.

  4. redis uses single thread so fast

    Many people misunderstand the relationship between multithreading and high performance

    • Myth 1: high performance servers must be multi-threaded
    • Myth 2: the efficiency of multithreading must be faster than that of single thread

    To avoid these two misunderstandings, we must first understand that multithreading is based on CPU context switching, which is very time-consuming. The core of redis is based on memory. In computer, the speed of CPU is slower than that of memory, so multiple reads and writes are on one CPU, and based on memory, single thread is the optimal solution.

    In general, the following points: (based on the hardware level)

    • redis is based on memory, and the reading and writing speed of memory is very fast;
    • redis saves a lot of context switching time;

    Another point: (based on the technical level of algorithm)

    • redis uses multiplexing technology to handle concurrent connections;

data type

  1. Redis-key

    redis:0>set name zhang 
    "OK"
    redis:0>get name
    "zhang"
    redis:0>set age 24
    "OK"
    redis:0>keys *    # View all key s
     1)  "age"
     2)  "name"
    redis:0>exists name  #Judge whether there is a key. If there is a key, return 1 and if there is no key, return 0
    "1"
    redis:0>exists name1
    "0"
    redis:0>move name 1   # Remove a key
    "1"
    redis:0>keys *
     1)  "age"
    redis:0>set name zhang
    "OK"
    redis:0>keys *
     1)  "age"
     2)  "name"
    redis:0>expire name 10    # Set the expiration time of the key
    "1"
    redis:0>ttl name    # Check the remaining time of the key, - 2 means it has expired
    "5"
    redis:0>ttl name
    "3"
    redis:0>ttl name
    "1"
    redis:0>ttl name
    "-2"
    redis:0>get name
    null
    redis:0>type age     # View the type of key
    "string"
    
  2. Five common data types

    • String (string)

      redis:0>set key1 v1
      "OK"
      redis:0>keys *
       1)  "key1"
      redis:0>append key1 hello   # Append a string. If the current key does not exist, it is equivalent to set key
      "7"
      redis:0>get key1
      "v1hello"
      redis:0>strlen key1   #Get length
      "7"
      ####################################################
      
      redis:0>set views 0     # Set the initial traffic to 0
      "OK"
      redis:0>incr views     # Self increasing, equivalent to i++
      "1"
      redis:0>incr views
      "2"
      redis:0>incr views
      "3"
      redis:0>get views
      "3"
      redis:0>decr views  #Self subtraction, equivalent to i--
      "2"
      redis:0>decr views
      "1"
      redis:0>get views
      "1"
      redis:0>incrby views 10  # Self increment by user-defined step
      "11"
      redis:0>incrby views 10
      "21"
      redis:0>decrby views 5   # Self subtraction by user-defined step
      "16"
      redis:0>decrby views 5
      "11"
      redis:0>get views
      "11"
      #####################################################
      
      redis:0>set key1 "hello,zhang"
      "OK"
      redis:0>get key1
      "hello,zhang"
      redis:0>getrange key1 0 3     # Intercept string
      "hell"
      redis:0>getrange key1 0 -1
      "hello,zhang"
      redis:0>set key2 abcdefg
      "OK"
      redis:0>get key2
      "abcdefg"
      redis:0>setrange key2 1 xx    #Replace string
      "7"
      redis:0>get key2
      "axxdefg"
      
      ###################################################
      
      redis:0>keys *
       1)  "key2"
       2)  "key1"
      redis:0>setex key3 30 hello   # Set the expiration time at the same time
      "OK"
      redis:0>get key3
      "hello"
      redis:0>ttl key3
      "20"
      redis:0>setnx mykey redis    # It can only be set when there is no key (often used in distributed locks)
      "1"
      redis:0>key *
      "ERR unknown command `key`, with args beginning with: `*`, "
      redis:0>keys *
       1)  "key2"
       2)  "mykey"
       3)  "key1"
      redis:0>ttl key3
      "-2"
      redis:0>setnx mykey Mondodb
      "0"
      redis:0>keys*
      "ERR unknown command `keys*`, with args beginning with: "
      redis:0>keys *
       1)  "key2"
       2)  "mykey"
       3)  "key1"
      redis:0>get mykey
      "redis"
      
      
      #########################################################
      
      redis:0>mset k1 v1 k2 v2 k3 v3   # Set multiple values at the same time
      "OK"
      redis:0>keys *
       1)  "k2"
       2)  "k3"
       3)  "k1"
      redis:0>mget k1 k2 k3     # Get multiple values at the same time
       1)  "v1"
       2)  "v2"
       3)  "v3"
      redis:0>msetnx k1 v1 k4 v4
      "0"
      redis:0>get k4
      null
      
      ###########################################################
      redis:0>mset user:1:name zhang user:1:age 24    # This is equivalent to creating a user object with ID 1 and attributes name and age
      "OK"
      redis:0>mget user:1:name user:1:age
       1)  "zhang"
       2)  "24"
       
       ########################################################
       redis:0>getset db redis   # First get in set, and return null if the value does not exist
      null
      redis:0>getset db mongodb  # If it exists, first obtain the original value and set a new value
      "redis"
      

      String similar usage scenario: value can be a number in addition to a string

      • Counter
      • Number of fans in multiple units
      • Number of fans
      • Storage of object cache
    • List

      In redis, we can regard list as stack, queue and blocking queue!

      All list commands start with l

      redis:0>lpush list one           # Set one or more values. Insert into head (left)
      "1"
      redis:0>lpush list two
      "2"
      redis:0>lpush list three
      "3"
      redis:0>lrange list 0 -1     # Get the value in the list
       1)  "three"
       2)  "two"
       3)  "one"
      redis:0>lrange list 0 1     # Obtain specific value through interval
       1)  "three"
       2)  "two"
      redis:0>rpush list right
      "4"
      redis:0>lrange list 0  # Set one or more values. Insert to tail (right)
       1)  "three"
       2)  "two"
       3)  "one"
       4)  "right"
       
       
       #########################################################
       
       redis:0>lrange list 0 -1
       1)  "three"
       2)  "two"
       3)  "one"
       4)  "right"
      redis:0>lpop list      # Remove the first value of the header
      "three"
      redis:0>lrange list 0 -1
       1)  "two"
       2)  "one"
       3)  "right"
      redis:0>rpop list     # Remove the first value of the tail
      "right"
      redis:0>lrange list 0 -1
       1)  "two"
       2)  "one"
       
       
       ############################################################
       redis:0>lrange list 0 -1
       1)  "two"
       2)  "one"
      redis:0>lindex list 0    # Obtain values according to the following table
      "two"
      redis:0>lindex list 1    # Obtain values according to the following table
      "one"
      redis:0>llen list        # Returns the length of the list
      "2"
      
      ###########################################################
      
      redis:0>lrange list 0 -1
       1)  "three"
       2)  "three"
       3)  "two"
       4)  "one"
      redis:0>lrem list 1 one     # Remove the value of the specified number in the list
      "1"
      redis:0>lrange list 0 -1
       1)  "three"
       2)  "three"
       3)  "two"
      redis:0>lrem list 1 three
      "1"
      redis:0>lrange list 0 -1
       1)  "three"
       2)  "two"
      redis:0>lpush list three
      "3"
      redis:0>lrem list 2 three
      "2"
      redis:0>lrange list 0 -1
       1)  "two"
       
       ###################################################
       ltrim  # Intercept the specified length in the list through the following table, and the length of the list will change
       rpoplpush  # Move the value in the list (pop it up first and insert it later)
       lset   # Replace the value specified in the following table with another value. If there is no value, an error will be reported, and if there is, it will be updated
       linsert. # Inserts a value before or after the specified value
      

      Summary

      • It is actually a list. Before node, after, left and right can insert values
      • If the key does not exist, create a new linked list
      • If the key exists, add content
      • If all values are removed, the empty linked list also means that it does not exist
      • Insert or change the value on both sides for the highest efficiency! Intermediate elements, lower relative efficiency
    • Set

      The values in set cannot be repeated and unordered

      sadd     # add value
      smembers   # View all values in set
      sismember   # Judge whether the current value is in the set
      scard    #View the number of set values
      srem   # Removes the specified element from the set
      srandmember  # Select an element at random
      spop    # Randomly delete an element
      smove   # Move a specified value to another set set
      sdiff  # Find the difference set between two sets
      

      Realize the functions of common concern and second friends.

    • Hash (hash)

      The essence of map set and key value is not much different from String type

      hset   # add to
      hget   # obtain
      hmset  # Set multiple values at the same time
      hmget  # Get multiple values at the same time
      hgetall # Get all values in the form of key and value
      hlen    # Get the number of fields in the hash table
      hexists # Determine whether the field exists
      hkeys   # Only get all key s
      hvals   # Get all values only
      hincrby # Specify increment
      hsetnx  # If it does not exist, it can be created. If it exists, it cannot be set  
      

      It is used to save frequently changed information, especially user information

    • Zset (ordered set)

      It is similar to set except that the score parameter is added.

      zadd      # add to
      zrange.   # Get all
      zrangebyscore.  # Output from small to large according to score
      zrem.     #  remove
      zrevrange # From large to small output
      zcount   # Get length
      

      Application scenario: leaderboard, weighted collection

  3. Three special data types

    • geospatial (geographic location)

      `geoadd`       # add to
      # The command takes the parameters x,y in the standard format, so the longitude must precede the latitude. The limits of these coordinates can be indexed, and the area can be very close to the pole, but can not be indexed. Specific restrictions are specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 as follows:
      # The effective longitude is from - 180 degrees to 180 degrees.
      # The effective latitude ranges from -85.05112878 degrees to 85.05112878 degrees.
      # When the coordinate position exceeds the above specified range, the command will return an error.
      
      `geopos`     # Obtain longitude and latitude according to key
      
      `geodist`  # Gets the straight-line distance between two positions
      # The parameter unit of the specified unit must be one of the following units:
      # m is expressed in meters.
      # km is expressed in kilometers.
      # mi is expressed in miles.
      # ft is in feet.
      
      `georedius`   # Obtain the data within the specified radius (or specify the quantity), such as city, user, etc
      
  • hyperloglog (cardinality)

    What is cardinality

    A{1,3,5,7,8,7}

    B{1,3,5,7,8}

    Cardinality {non repeating element} = 5, acceptable error

    brief introduction

    redis2. Version 8.9 updates this data structure, which is an algorithm for cardinality statistics

    Advantages: the occupied memory is fixed, 2 ^ 64, only 12kb

    Disadvantages: there is an approximate value of 0.81% standard error

    Number of visits to the website (one person visited many times, but still one person)

    In the traditional way, set saves the user id, and then counts the number of set activation as the standard judgment. In this way, it will be very troublesome to take shares and save a large number of user IDs! Our goal is to count, not save the user id.

    my:0>pfadd a b c d e f g       # Create a set of elements a
    "1"
    my:0>pfcount a           # View the number of elements in a group
    "6"
    my:0>pfadd a1 b c 1 2 5 g
    "1"
    my:0>pfcount a1
    "6"
    my:0>pfmerge a2 a a1     # Combine two groups of elements to get non duplicate elements
    "OK"
    my:0>pfcount a2
    "9"
    

    If fault tolerance is allowed, you can use hyperloglog,

    Not allowed, use set.

  • bitmaps (bitmap)

    Bit storage (save data with only two states, save with 0 and 1)

    1. Count the number of people infected by the epidemic
    2. Statistics of user information, active or inactive
    3. Login, not login
    4. Punch in, not punch in
    # Clock in a week
    my:0>setbit sign 0 1
    "0"
    my:0>setbit sign 1 0
    "0"
    my:0>setbit sign 2 0
    "0"
    my:0>setbit sign 3 1
    "0"
    my:0>setbit sign 4 1
    "0"
    my:0>setbit sign 5 0
    "0"
    my:0>setbit sign 6 0
    "0"
    
    # Check whether to punch in a certain day
    my:0>getbit sign 3
    "1"
    my:0>getbit sign 6
    "0"
    
    # Count clock in days
    my:0>bitcount sign
    "3"
    

affair

A single redis command is atomic, but transactions do not guarantee atomicity

redis transaction essence: an opportunity for a set of commands! The index commands in a transaction will be serialized and executed in sequence during the execution of the transaction.

Features: disposable, sequential and exclusive! Execute a series of commands.

redis transaction has no concept of isolation level!

All commands are not executed directly in the transaction. They will be executed only when the execution command is initiated! Exec

redis transactions:

  • Open transaction (multi)

  • Order to join the team (.)

  • Execute transaction (exec)

hz:1>multi
"OK"
hz:1>set k1 v1
"QUEUED"
hz:1>set k2 v2
"QUEUED"
hz:1>get k1
"QUEUED"
hz:1>set k3 v3
"QUEUED"
hz:1>exec         # The execution of this command is equivalent to the end of the current transaction. To use the transaction, you need to start it again
 1)  "OK"
 2)  "OK"
 3)  "v1"
 4)  "OK"

discard transaction

hz:1>multi
"OK"
hz:1>set k1 v2
"QUEUED"
hz:1>set k4 v4
"QUEUED"
hz:1>discard
"OK"
hz:1>exec
"ERR EXEC without MULTI"
hz:1>get k4
null

Compile type exception (there is a problem with the code and the command is wrong). Are there any exceptions in the transaction and the command will not be executed

hz:0>multi
"OK"
hz:0>set k1 v1
"QUEUED"
hz:0>getset k2
"ERR wrong number of arguments for 'getset' command"
hz:0>set k3 v3
"QUEUED"
hz:0>exec
"EXECABORT Transaction discarded because of previous errors."
hz:0>get k1
null

Runtime exceptions (such as 1 / 0). If there are syntax errors in the queue, other commands can be executed normally when executing the command, and the error command will be thrown

hz:0>multi
"OK"
hz:0>set k1 "v1"
"QUEUED"
hz:0>incr k1
"QUEUED"
hz:0>set k2 v2
"QUEUED"
hz:0>exec
 1)  "OK"
 2)  "ERR value is not an integer or out of range"
 3)  "OK"
hz:0>get k1
"v1"

Monitoring - redis lock command: watch

Pessimistic lock: very pessimistic. I think there will be problems at any time. No matter what I do, I will lock it

Optimistic lock: very optimistic. I think there will be no problem at any time. I will judge whether the data is modified only when updating the data

  • Get version (watch key)
  • When updating data, compare version
watch money  # Equivalent to obtaining version

# Transaction failed
unwatch money # Unlock first, lock again, and reopen the transaction

Learning source: Crazy God says Javabilibili

Tags: Java Redis

Posted by manalnor on Mon, 23 May 2022 07:29:25 +0300