This is the 25th day of my participation in the August Challenge

Redis

Redis is a high performance key-value pair developed in C language. It is a non-relational database based on memory, which can be used as database, cache, message middleware, etc.

The advantages of Redis

  • Based on memory operation, excellent performance, very fast read and write speed.

  • Multiple data types are supported. It includes five basic data types: String, List, set, Hash, and sortedSet, and three special data types: Geospatal, HyperLogLog, and BitMaps.

  • Data persistence is supported. Redis provides two persistence modes, AOF and RDB, to persist the data in the memory to the disk. When Redis restarts, the data saved to the disk will be loaded to the memory.

  • Can be used as messaging middleware to support publish subscriptions

  • Master/slave replication, sentinel, high availability. Redis supports master-slave replication, which allows data from one primary Redis server to be copied to another secondary Redis server, and provides sentinel mode (that is, when the primary node fails, a new primary node is automatically selected) to ensure high availability in the Redis cluster environment.

Five basic data types

🚨 Note: the following data type refers to the data type of the Redis value, and the Redis key is always of type string.

String string

String is the most basic data type of Redis. A key corresponds to a value, which can be either a string or an integer.

Common operation
  • get key(Obtain the corresponding value according to the key)
  • set key value(Add a key-value pair)
  • del keyDelete key/value pairs based on key
  • mset key1 value1 key2 value2..(Add multiple key-value pairs at once)
  • mget key1 key2 ..(Get the value of multiple key-value pairs at once based on multiple keys)
  • strlen key(The character length of the value of the corresponding key-value pair based on the key)
  • append key valueAppends the specified string to the value corresponding to key in the key-value pair.

✨ String is stored in Redis as a string by default. When using INCr or DECr operations, string values are converted to integer or floating point values and then evaluated. 🚨 Note: An error is reported if the original data type cannot be converted to an integer or floating-point type, or if the value being processed exceeds the maximum value of the redis numerical calculation (the maximum value of long).

  • Incr key (add value of key +1)

  • Incrby key value (add the value of the key to the specified integer value)

  • Incrbyfloat Key value (adds the value of the value corresponding to the key to the specified single float value)

  • Decr key(decr key value -1)

  • Decr key value (subtract the value of the key from the specified integer value)

⏰ Sets the validity period of key/value pairs

  • Setex key value

  • Psetex key ms value

Application scenarios

For example, if you like an article in nuggets, increase the number of likes and show the number of page views.

  1. Initialize the
  • set post:id:00001:views 0
  • set post:id:00001:live 0
  1. Increase likes, increase views, display views:
  • incr post:id:00001:live

  • incr post:id:00001:views

  • get post:id:00001:views

Hash hash

Hash data type is a collection of multiple key-values. It can be regarded as key-map {(field1, value1), (field2, value2)… }, a mapping consisting of the field and value associated with the field and value are strings, in which Map can store 2^32-1 field-value key-value pairs. Duplicate keys are not allowed to be stored, especially suitable for storing objects.

Common operation
  • Hset Key Field Value Stores a field value key value pair

  • hmset key field1 value1 field2 value2… Store multiple field values at a time

  • Hget key field Retrieves the value of the specified field

  • Hgetall Key retrieves all fields and values, which is inefficient

  • Hmget key field1 field2 Obtains multiple field values at a time

  • Hlen key gets the set length

  • Hdel key field Deletes the specified key-value pair based on the key and field

  • Hexists Key Field Determines whether a key in the hash exists

  • Hkeys key retrieves all fields

  • Hvals key Retrieves all values

  • Hincrby Key field autoincrement Increments the value of the specified field (specified autoincrement)

  • Hincrbyfloat Key Field Auto-increment Indicates that the value corresponding to the specified field is auto-increment (specified auto-increment). The value is a floating point type

  • Hsetnx Key Field Value If there is no specified field in the hash set, the field pair can be added

  • Hlen key Gets the number of hash tables

  • Hexists Key field Tests whether the field of the specified hash exists (1 is returned if it does)

  • Hkeys key Retrieves all fields based on the key

  • Hvals key Retrieves the values of all fields based on the key

Application scenarios

The Hash data type implements basic operations in the shopping cart, such as selecting all items in the cart, removing items, and increasing/decreasing the number of items to be purchased. As shown in the figure below, a user ID is used as the key to create a hash storage structure for each user to store the shopping cart information corresponding to that user, which involves the following operations:

  • Filed (Commodity ID) Value (Commodity quantity)

  • Display all items in shopping cart and the corresponding quantity of each item: hgetall key

  • Increase or decrease the number of items: Hincrby Key (User ID) Field (Item ID) 1(Quantity +1)/-1(Quantity -1)

  • Delete the selected item: hdel key(user ID) field(product ID)..

  • Get shopping cart amount: hlen key(user ID)

🚨 note: The above operation does not speed up the rendering speed of shopping cart page, because the field in our hash stores the ID of the product, and to display the information corresponding to the product, we need to query the database according to the ID of the product and then return the display, so we can define another field-value pair to store the product information. Use hsetNx key(user ID) field2(commodity ID) value2(Commodity information)

List the list

The list data type is a simple ordered list of strings, which saves all the data in the string type. The bottom layer is implemented by the bidirectional linked list storage structure. You can add an element to the left or right side of the list, you can take an element from the left or right side of the list, you can store duplicate elements, up to 2^32-1 elements.

Common operation
  1. Add:
  • lpush key value1 value2.. Add an element to the left side of the list (you can add more than one at a time) and return the length of the added collection

  • Rpush key Value adds the element to the right of the list

  • Linsert key before/ After “value1” value2 Inserts value2 into the specified list with value before or after value1

  1. Access to:
  • Lrange Key start end Indicates the range

  • Lindex key index gets the element at the specified position

  • Llen Key gets the number of elements in the list collection

  1. Get and remove data:
  • lpop key: Removes the leftmost element of the list and returns the element

– rpop key: deletes the right-most element in the list and returns the element

  1. Extend the operation
  • blpop key[key …] Timeout Retrieves the element to the left of the collection and sets the survival time (in seconds) for retrieving the element. Setting this value does not remove the element immediately as lPOP does.

  • brpop key[key ...] timeout

  • Lrem key count value Deletes the value element specified in the set with the specified key. If there are multiple elements to be deleted in the set, count can be used to specify the number of deleted elements.

Application scenarios

For example, “like” in wechat circle of friends will display friends’ information in the order of “like”. This can be achieved by using the id of the article in moments as the key and value as the information of the “like” friend, involving the following operations:

  • Rpush key(article ID) value(friend information) like

  • Lrem key(post ID) count(number of posts removed, here is 1) value(friend information) Unlike

  • Lrange Key (Article ID) 0-1 Displays all thumbs-up information in sequence

Set the set

A set is an unordered, non-repeatable collection of strings, and its underlying implementation is via HashTable.

Common operation
  • Sadd key member [member….]

  • Gets the sMembers keys of all elements in the set collection

  • Delete an element srem key value from the set

  • Check whether the specified sismember key value element exists in the set

  • View all values of the specified set collection smembers keys

  • Gets the number of elements in the specified set scard key

  • Retrieves a random element srandMember key from the specified set

  • Srandmember key n randomly fetch n elements from the specified set

  • Removes random elements from the specified set and returns the spop key of the deleted element

  • Moves the specified value in one set to the key in another set. Smove The element to be moved in the key source of the target set

  • Sdiff key1 key2 [key…

  • Sinter key1 key2 [key…]

  • Get the union between the specified two sets sunion key1 key2 [key…

  • Gets the union between the specified two sets and saves it in another new set. Sunionstore Key of the new set key1 key2 [key…]

Application scenarios
  • For wechat lottery, use sadd key userId to save the userId participating in the lottery into the set. Use the command smembers key to view all elements of the set, and randomly select the winners by command spop key number. After using the spop command, the id of the user who has won the prize will be removed from the set set (so as to realize that the user who has won the prize cannot participate in the drawing of the next prize), and the user ID of the user who has won the prize will not be deleted from the set set after randomly drawing the winner with the number of Srandmember key.

  • For example, to obtain the common concerns of two users in microblog 🏆, the respective concerns of two users can be stored in the set set of sadd user ID followed information, and then through sinter user 1Id user 2Id, the intersection of the big V concerned by the two users can be obtained, which is their common concerns.

  • Website traffic statistics.

    1. PV(the number of visits to the website will be +1 when refreshing the page view), using string type can be achieved, call incr key to increase the page view, get key to obtain the total page view.
    2. UV(the number of times the site is accessed by the user, according to the userId to statistics), using the set set of data to re-function, using a set set to store the id of the user visiting the site, call sadd userId when visiting the site, when the same user for many times, when the first visit to add will not succeed, so as to achieve UV statistics.
    3. IP(the number of times a website is accessed by different IP addresses, the IP address remains unchanged, the user changes, and the number of IP visits remains unchanged), the statistics of the deduplication using the set set, and the access IP is saved in the set set.

Ordered set sortedset

An ordered set sortedset, also called a Zset, is a set of elements of type string like a set. It is not allowed to store duplicate elements. Unlike a set, a Zset can associate a parameter score with a weight of type Double. The elements put into the collection are sorted by this parameter score, so Zset is an ordered collection.

Common operation
  • storageZadd key score value

🚨 Note: If the same data is added repeatedly, the score value will be overwritten. The following is an example:

127.0.0.1:6379> zadd zkey2 2 test (integer) 1 127.0.0.1:6379> zadd zkey2 3 test (integer) 0 127.0.0.1:6379> zscore zkey2 The test of "3" 127.0.0.1:6379 >Copy the code
  • Zrange key start value [withscores]

  • Get the number of elements in an interval zcount key min Max

  • Zrangebyscore key min Max [withscores]

  • Example Delete the Zrem key value

  • Zremrangebyrank key start stop removes elements from the specified range based on the sorted collection

  • Delete the element zremrangeByScore key min Max from the specified interval according to score

  • View the number of elements in the ordered set with the specified key zcard key

  • Zcount key start end [withscores]

  • Zrevrange key start end [withscores]

  • Find the intersection of two or more sets and store the intersection ina new set. Zinterstore Destination (store the resulting intersection) NumberKey (Number of sets to perform intersection operations) key1 key2 [key…]

  • Find the union of two or more sets and save the intersection ina new set. Zunionstore Destination (store the resulting union) NumberKey (Number of sets to perform the union operation) Key1 key2 [key…]

  • Invert elements of an interval in the set according to score zrevrangebyscore key Max min [withscores]

  • Zrangebyscore key -INF + INF [withscores] zrangebyScore key -INF + INF [withscores]

127.0.0.1:6379> zadd Salary 2500 xiaoming (integer) 1 127.0.0.1:6379> Zadd salary 2000 xiaohong (integer) 1 127.0.0.1:6379> zadd salary 3000 libai (integer) 1 127.0.0.1:6379> zrangebyscore salary - INF + INF 1) "xiaohong" 2) "Xiaoming" 3) "libai" 127.0.0.1:6379> zrangebyscore score - INF + INF withscores 3) "xiaoming" 4) "2500" 5)"libai" 6) "3000"Copy the code
  • Gets the index of the specified element in the collection

  • Zscore key member zscore key member

  • Modify the score value zincrby key increment corresponding to the specified element in the set

127.0.0.1:6379> zscore zkey1 zvalue2 "3" 127.0.0.1:6379> zincrby zkey1 1 zvalue2 "4" 127.0.0.1:6379> zincrby zkey1 2 Zvalue2 "6" 127.0.0.1:6379> zincrby zkey1-2 zvalue2 "4"Copy the code
Application scenarios

For example, in the top search version, the article ID is the key and the amount of search is the score

The key operation

Sets the specified validity period for key

  • Expire key seconds Specifies the number of seconds after the key expires

  • Pexpire key milliseconds Specifies how many milliseconds after the key expires

  • Expireat Key timestamp Sets the expiration time in the form of a timestamp

  • Pexpireat key milliseconds-timestamp Specifies the expiration time in the format of timestamp + ms

Gets the validity time of the key

  • ttl key

  • pttl key

Change the key from time-sensitive to permanent

  • persist key

Key Query operations

  • keys pattern

  • Pattern Matching mode

    1. keys *Query all
    2. keys pro*Query all keys that start with Pro
    3. keys am*Query all keys that end in “AM”
    4. keys ?? proQuery all keys that start with any two characters and end with pro
    5. keys pro?Query all keys that start with pro and contain an arbitrary character at the end
    6. keys no[a|b]proQuery all keys that start with no, end with pro, and middle with A or B

🏁 the above is a brief introduction to Redis, if there are any mistakes, please leave a comment, if you think this article is helpful to you, please like 👍 😋😻 👍