1. Data type of Redis

Redis supports five data types: string,hash,list,set, and ZSet.

2.String

2.1 introduce Sting

1. String is the most basic redis type. You can think of it as Memcached.

2. String is binary safe. The redis string can contain any data. Like JPG images or serialized objects.

2.2 characteristics of String

1. The string type is the most basic data structure of Redis. First, the key is the string type, and other structures are built on the basis of the string type, so the string type can be the basis for learning and respecting the other four data structures.

2. String types can actually be strings (simple string, complex string (XML, JSON), numbers (integer, floating point), and binary (image, audio, video).

2.3String Application Scenarios

1. Cache function: The most classic use scenario of strings, redis is the cache layer, Mysql as the storage layer, most of the requested data is obtained from Redis, because Redis has the characteristics of supporting high concurrency, so cache can usually play a role in accelerating read and write and reducing back-end pressure.

2. Counter: Many applications will use Redis as the basic tool of counting, which can realize the functions of fast counting and query cache, and the data can be landed to other data sources one step at a time. For example, the number of videos played, the number of comments, likes and shares on Weibo, the number of douyin works collected, the number of sales and comments of JINGdong products, etc. The system uses Redis as the basic component of video playback count.

3. Shared session: In cluster mode, the session replication function provided by the container can be generally used when there are not many applications. When the number of applications increases and the system is relatively complex, session services centered on the memory database such as Redis are generally set up. Session is no longer managed by the container. Instead, it is managed by the Session service and an in-memory database. In this mode, as long as the high availability and scalability of Redis is guaranteed, every time to obtain user updates or query login information is directly centrally obtained from Redis.

4. Rate limiting: To ensure security, users are required to enter the mobile phone verification code each time they log in. To prevent frequent access to the SMS interface, users are limited in obtaining the verification code every minute.

2.4String Common Commands

01 set02 get: used to obtain the value of the specified key. 03 setnx: used to set the value of the specified key. If the key already exists, 0 is returned. Nx: Not exist 04 setex: Used to set the value of the key and specify the validity period of the key. 10 seconds later, the value is null. 05 setrange: rewrites the value of the specified key from 4 to Ming. The final result is xiaoming 06. Username, age, and sex correspond to wangwu, 10, and 107msetnx respectively: Set the value of the key in batches. If the key already exists, 0 is returned. 08 getSet: Sets a new value for the specified key and returns the original data. 09 getrange: returns a substring of a string, which is equivalent to string interception. Subscript 0 is the start position and subscript 3 is the end position. 10 mGET: obtains the values of keys in batches and displays them in sequence. 11 incrby: specifies how much to increase the number stored in the specified key. 12 DECr: subtracts the number stored in the specified key by one. The value must be a number. 13 decrby: specifies how much to reduce the number stored in the specified key. 14 Append: appends the value in the specified key. 15 strlen: Returns the length of the value in the specified keyCopy the code

3. Hash

3.1 introduce the Hash

Redis hash is a set of key/value pairs, similar to Java Map

,
,object>

Redis hash is a mapping table of fields and values of string type. Hash is especially suitable for storing objects.

3.2 Application Scenarios of Hash

The hash structure is more intuitive than string serialization cache information and is easier to update.

So store some structured data, such as the user’s nickname, age, gender, points, etc., store a user information object data and can be shopping cart.

3.3 the orders of the Hash

Hset key field value Sets one hash, but only one attribute can be set at a time. To set multiple attributes in batches, run the hmset command. 2. You can only obtain the value of one attribute at a time. To obtain the value of a batch attribute, run the hmget 3.hmset key field value[(field value)... Set a hash, for example: Hmset key1 name lonely age 18, this command generates a hash with the key key1, the hash contains two attributes: name and age, the corresponding values are lonely and 18. Returns the value of key-name in the hash corresponding to the specified key. For example, the result of calling hmget key1 name is the hash corresponding to key1. 5. Hdel key field... Delete the specified field from the hash corresponding to the specified key... The information. For example, key1:{name:lonely,age:25}, run the hdel key1 age command. The result is that the age attribute is deleted, That is, only key1:{name:lonely} is left. 6. Hlen key Returns the number of key-value pairs in the hash corresponding to the specified key For example, if key1:{name:lonely,age:25} exists, then {name,age} is the result of hkeys key1 and hkeys keys. Hgetall key Returns information about all key/value pairs corresponding to the specified key 10. Hincrby key field increment Increment the value of the specified attribute in the hash corresponding to the specified key by 10 increments the value of the specified attribute in the hash corresponding to the specified key by 10 increments the value of the specified attribute in the hash corresponding to the specified key by 10 incrementsCopy the code


4.List

4.1 the List is introduced

A Redis list is a simple list of strings, sorted by insertion order. You can add an element to either the head (left) or the tail (right) of the list. It’s actually a linked list underneath

4.2 a List of features

1. The list type is used to store multiple ordered strings, each of which is called an element.

2. In Redis, you can insert (PUBSH) and pop (pop) at both ends of the queue table. You can also get the list of elements in a specified range and the elements of the table under a specified index.

3. A list is a flexible data structure that can act as a stack and queue. A list can store up to 233-1 elements (4294967295, each list can store more than 4 billion).

4. The elements of a list are ordered, which means that a list of elements in a range or scope can be retrieved by index subscript. The elements in a list can be repeated.

4.3 Application Scenarios of List

1. Message queue: The combination of Lpush + BRPOP commands of Redis can implement blocking queue. The producer client inserts elements from the left side of the list with LUPsh, and multiple consumer clients “grab” elements at the end of the list with BRPOP command blocking

2. Article list: Each user has their own article list, now need paging display article list, at this time you can consider using the list, the list is not only in order and support to obtain elements according to the index range.

3. Latest list: Lpush command and lrange command of list type can realize the function of the latest list. Each time, lpush command can insert new elements into the list, and then read the latest element list through lrange command, such as the “like” list and comment list in the moments of friends.

4.4 Common Lsit Commands

01 lpush: Adds one or more elements to the head of a list. Returns the number of elements in the list. 02 lrange: Returns elements in the specified range in the list collection, with 0 subscript for the first element and -1 for the last element. 03 rpush: Add one or more elements to the end of the list, return the number of elements in the current list, using a queue. 04 linsert: inserts an element before or after the specified element in the list. 05 lset: sets the index of the specified element in the list. The index 0 represents the first element. 06 LREM: Delete the element with the same N and value from the corresponding list."lrem list 1 noe"Select * from list where 1 is the same as noe. 08 lPOP: Removes an element from the head of the list, and returns the value of the deleted element. 09 RPOP: Removes an element from the end of the list and returns the value of the deleted element. 10 rpoplpush: Remove an element from the end of the first list and add it to the end of the second list. 11 Lindex: returns the value of the specified element in the list, starting with the element subscript 0. 12 llen: Returns the number of elements in the listCopy the code

5.Set

5.1 the Set is introduced

Redis’ Set is an unordered collection of type string. It is implemented through a HashTable.

5.2 the Set features

1. A set is also an element that holds multiple strings, but unlike a list, no duplicate elements are allowed in a set.

2. Elements in a set are unordered and cannot be retrieved by index subscripts.

3. Redis not only supports adding, deleting, changing and searching within collections, but also supports taking intersection, union and difference sets of multiple collections, and makes reasonable use of collection types, which can solve many practical problems in practical development

5.3 Application Scenarios of SET

1. Interested in friends/concern/fan/set: the set type unique features make it suitable for storing buddy/concern/fan/people who are interested in collections, the number of elements in collection may be many, each time all out cost, the set type provides some useful commands are used to directly manipulate these collections, For example, the command a. sinter can be used to obtain the common friends of users A. sismember can be used to determine whether A is a friend of B. scard can be used to obtain the number of friends D. sinter can be used to obtain the common friends of users A and B. The smove command can transfer B from A’s set of fans to A’s set of friends

2. Random display: The display area of the home page of the app is limited, but fixed contents cannot always be displayed. One way is to determine a batch of contents to be displayed first, and then obtain them randomly. A total of 200 hit songs yesterday, home page random display 30.

3. The label (tag) : set collection type is a typical usage scenarios, such as a user interested in entertainment, sports comparison, another may be interested in the news, the interest is the label, with these data can get the same label, the label and the common interest of the user, we blog sites are often used to interest in the label, Take users with the same hobbies and similar content and merge them with a tag.

4. Mutual friends feature: Shared likes, or extended apps like second friends.

5. Count the independent IP of the website: the use of set set elements are not unique, can quickly count the independent IP of the website.

6. Blacklist/whitelist: For security purposes, users, IP addresses, and devices need to be blacklisted. The set type is suitable for storing these blacklist data.

7. Other applications: Generate random numbers, such as raffles

4.4 Common commands of Set

1 SADD key member1 [member2] Adds one or more members to the set. 2 SCARD key gets the number of members of the set. 3 SDIFF key1 [key2] Returns the difference set of all sets given. 4 SDIFFSTORE Destination SINTER key1 [key2] returns the intersection of all the given sets. 6 SINTERSTORE Destination key1 [key2] 7 SISMEMBER Key member Determines whether the member element is a member of the set key. 8 SMEMBERS Key Returns all members of the set. 9 SMOVEsourceDestination member takes the member element fromsourceSRANDMEMBER key [count] Returns one or more random numbers in the set. 12 SREM key member1 [member2] 13 SUNION KEY1 [KEY2] Returns the union of all given sets 14 SUNIONSTORE Destination KEY1 [KEY2] The union of all given sets is stored in the Destination set 15 SSCAN key Cursor [MATCH Pattern] [COUNT COUNT] Iterates over the elements in the setCopy the code

6.ZSet(sorted set)

6.1 introduce ZSet

Redis zset, like set, is a collection of string elements and does not allow duplicate members. The difference is that each element is associated with a double score.

Redis uses scores to sort the members of a collection from smallest to largest. Members of a Zset are unique, but scores can be repeated.

6.2 ZSet characteristics

ZSet retains the feature that sets cannot have duplicate members, but the difference is that the elements in ordered sets can be sorted, but unlike lists, which use index subscripts as the basis for sorting, ZSet assigns a score to each element as the basis for sorting.

6.3ZSet Application Scenarios

List: 1. Ordered set classic usage scenarios, such as jingdong daily sales ranking, jingdong’s monthly sales list, product list, according to the time of the new video website need for users to upload video to do list, list maintenance may be various: in accordance with the time, according to the amount of broadcast, according to the number, etc.

6.4 Common ZSet Commands

1.ZADD key score1 member1 [score2 member2] Adds one or more members to the ordered set, 2 ZCARD key Obtains the number of members in the ordered set. 3 ZCOUNT key min Max Calculates the number of members in the ordered set. 4 ZINCRBY key increment Member Increment 5 ZINTERSTORE destination numkeys key [key...] Calculate the intersection of a given one or more ordered sets and store the result set in a new ordered set key 6 ZLEXCOUNT key min Max Calculate the number of members in the specified dictionary interval in the ordered set 7 ZRANGE key start stop [WITHSCORES] 8 ZRANGEBYLEX key min Max [LIMIT offset count] Returns the members of the ordered set through the dictionary range 9 ZRANGEBYSCORE key min Max ZREM key member [member...] [ZREM key member] 12 ZREMRANGEBYLEX key min Max Removes all members of the given dictionary range from the ordered set. 13 ZREMRANGEBYRANK key start stop Removes all members of the given ranking range from the ordered set ZREMRANGEBYSCORE key min Max Removes all members of a given range of scores from the ordered set. 15 ZREVRANGE key start stop [WITHSCORES] Returns the members of the specified range from the ordered set. 16 ZREVRANGEBYSCORE key Max min [WITHSCORES] Returns the rank of the members in the ordered set within the specified score range. 18 ZSCORE key member Returns the score value of the member in the ordered set 19 ZUNIONSTORE destination numkeys key [key...] 20 ZSCAN key CURSOR [MATCH Pattern] [COUNT COUNT] Iterates over the elements in the ordered set (including element members and element scores)Copy the code