Five data types and usage scenarios of Redis

Redis has five basic data structures: string, list, set, hash and zset.

All data structures of Redis are a key corresponding to a value. The difference between different types of data structures lies in the different structure of value. For example, string data type, its value is a string, list data type, and its value is a linked list.

1.String

String string is the simplest data structure of Redis. It can store strings, integers or floating-point numbers. The most common application scenario is object caching, such as caching user information. key is "userInfo" + #{user ID}, and value is the JSON string of the user information object.

Case:

key: userInfo123

value: {"gender": 1, "nickname": "java program fish", "userId": 123}

Redis String basic operations

127.0.0.1:6379> set name hzy # set up
OK
127.0.0.1:6379> get name # obtain
"hzy"
127.0.0.1:6379> exists name  # Judge whether it exists
(integer) 1
127.0.0.1:6379> del name # delete
(integer) 1
127.0.0.1:6379> get key
(nil)

Redis String batch operation

Multiple strings can be read and written in batches, saving network time and overhead.

127.0.0.1:6379> mset name1 xiaoming name2 xiaohong # Batch settings
OK
127.0.0.1:6379> mget name1 name2 # Batch acquisition
1) "xiaoming"
2) "xiaohong"

Redis String count operation

If the value is an integer, we can self grow it. There is a range of self growth. Its range is the maximum and minimum value of signed long. If this value is exceeded, Redis will report an error.

127.0.0.1:6379> incr likenum # Self increment 1
(integer) 1
127.0.0.1:6379> get likenum
"1"
127.0.0.1:6379> decr likenum # Minus 1
(integer) 0
127.0.0.1:6379> get number
"0"

Redis String expiration operation

127.0.0.1:6379> expire name 60 # Set timeout
(integer) 1
127.0.0.1:6379> setex name 60 value # Equivalent to setex + expire
OK
127.0.0.1:6379> ttl key # How long will the data expire
(integer) 11

The string is composed of multiple bytes, and each byte is composed of 8 bit s

Redis String usage scenario

  • Caching: as we usually develop, we often convert an object into a json string and put it into redis for caching

  • Counter: such as the number of blog posts read, comments, likes, etc

  • Self growth ID generated by distributed system

2. List

The Redis list is equivalent to the LinkedList in the Java language.

LinkedList advantages: high insertion performance, whether from the end or in the middle

LinkedList disadvantages: poor random reading performance, such as LinkedList The performance of get (10) is very low, because it needs to traverse the linked list and traverse the linked list from the beginning until it finds the element with index = 10.

How do Redis List data types implement queues?

Right in and left out

127.0.0.1:6379> rpush apps qq # Insert the element at the end of the list (rightmost)
(integer) 1
127.0.0.1:6379> rpush apps wechat taobao # Insert multiple elements at the end of the list (rightmost)
(integer) 3
127.0.0.1:6379> lpop apps # Removes and returns the first element of the list (leftmost)
"qq"
127.0.0.1:6379> lrange apps 0 1 # Returns the elements within the specified interval in the list. 0 represents the first, 1 represents the second, and - 1 represents the last
1) "wechat"
2) "taobao"
127.0.0.1:6379> lrange apps 0 -1 # -1 means the penultimate
1) "wechat"
2) "taobao"

Note: when the last element pops up in the list, the data structure will be deleted automatically and the memory will be recycled

How does Redis List data type implement stack?

First in, first out, right in, right out

127.0.0.1:6379> rpush apps qq wechat taobao
(integer) 3
127.0.0.1:6379> rpop apps # Remove the last element of the list, and the return value is the removed element
"taobao"

Redis List usage scenario

  • Asynchronous queue

  • Task polling (RPOPLPUSH)

  • Article list (lrange key 0 9)

3.Hash

Redis's Hash structure is equivalent to the HashMap of Java language, and its internal implementation structure is similar to jdk1 The HashMap of 7 is consistent, and the bottom layer is realized through data + linked list.

Redis Hash common commands

127.0.0.1:6379> hmset userInfo name "hzy" age "24" sex "1"
OK
127.0.0.1:6379> hexists userInfo name # Equivalent to containsKey() of HashMap
(integer) 1
127.0.0.1:6379> hget userInfo name # Equivalent to get() of HashMap
"hzy"
127.0.0.1:6379> hget userInfo age
"24"
127.0.0.1:6379> hgetall userInfo # When the amount of data is large, use it with caution! Gets all fields and values of the specified key in the hash table
1) "name"
2) "hzy"
3) "age"
4) "24"
5) "sex"
6) "1"
127.0.0.1:6379> hkeys userInfo # When the amount of data is large, use it with caution! Get key list
1) "name"
2) "age"
3) "sex"
127.0.0.1:6379> hvals userInfo # Get value list
1) "hzy"
2) "24"
3) "1"
127.0.0.1:6379> hset userInfo name "test" # Modify the corresponding value of a field
127.0.0.1:6379> hget userInfo name
"test"

Redis Hash usage scenario

  • Record the number of visitors to the whole blog (hyperlog is considered for the data volume, but there is a small error in this data structure. If the error cannot be accepted, other schemes can be considered)

  • Record the home page visits of a blogger in the blog, the blogger's name, contact information and address

4.Set

The set set of Redis is equivalent to the HashSet of Java. The set type in Redis is an unordered collection, and the elements in the collection have no order.

Add: HashSet is implemented based on HashMap. HashSet actually means that the elements in a set are disordered and cannot be repeated. The keys of HashMap are not in order. The order you insert them is different from the order of your iterative traversal, and the keys of HashMap are not repeated. HashSet is directly implemented based on HashMap.

Redis Set common commands

127.0.0.1:6379> sadd apps wechat qq # Add element
(integer) 2
127.0.0.1:6379> sadd apps qq # repeat
(integer) 0
127.0.0.1:6379> smembers apps # Note: the query order is inconsistent with that of the insert, because the set is out of order
1) "qq"
2) "wechat"
127.0.0.1:6379> scard apps # Get length
(integer) 2
127.0.0.1:6379> sismember apps qq # Use with caution! Check whether an element exists in the set. Only a single element can be received
(integer) 1
127.0.0.1:6379> sadd apps2 wechat qq
(integer) 2
127.0.0.1:6379> sinterstore apps apps apps2 # Get the intersection of apps and apps and store it in apps3
(integer) 1
127.0.0.1:6379> smembers app3
1) "qq"
2) "wechat"

Note: when the last element in the collection is removed, the data structure is automatically deleted and the memory is recycled

Redis Set usage scenario

  • Microblog lottery: if the amount of data is not particularly large, you can use spop (remove and return a random element in the set) or srandmember (return one or more random numbers in the set)

  • QQ tag: multiple notes for one user

  • Common concern (intersection)

  • Common friends (intersection)

5.sorted set

sorted set is an ordered set. sorted set adds a weight parameter score, so that the elements in the set can be arranged orderly according to the score, and the list of elements can be obtained through the scope of the score. This makes it similar to the combination of Java TreeSet and HashMap.

Sorted set common commands

127.0.0.1:6379> zadd apps 3.0 qq # Add the element to the sorted set. 3.0 is the value of score
(integer) 1
127.0.0.1:6379> zadd apps 2.0 wechat 1.0 aliyun # Add multiple elements at once
(integer) 2
127.0.0.1:6379> zcard apps # View the number of elements in the sorted set
(integer) 3
127.0.0.1:6379> zscore apps wechat # View the weight of a value
"2.0"
127.0.0.1:6379> zrange apps 0 -1 # Return the members in the specified interval of the ordered set through the index interval. 0 - 1 means to output all elements
1) "aliyun"
2) "wechat"
3) "qq"
127.0.0.1:6379> zrange apps 0 1 # Returns the members in the specified interval of the ordered set through the index interval
1) "aliyun"
2) "wechat"
127.0.0.1:6379> zrevrange apps 0 1 # Equivalent to the reversal of zrange
1) "qq"
2) "wechat"

Note: after the last value in the sorted set is removed, the data structure is automatically deleted and the memory is recycled

Sorted set usage scenario

  • Ranking List

  • Order payment timeout (insert when placing an order, member is the order number, score is the order timeout timestamp, and then write a scheduled task to execute zrange at regular intervals)

Keywords: Redis data structure Interview

Added by horsefaceba on Tue, 04 Jan 2022 02:25:06 +0200