Redis data type of Redis

1. Data type of Redis

    Redis supports five data types: string (string), hash (hash), list (list), set (unordered set) and ZSet (ordered set)

 2. String

   2.1 Introduction to Sting

      1. string is the most basic type of redis , you can understand it as the same type as Memcached, a key corresponds to a value, but the maximum cannot exceed 512M .

     2. The  string type is binary safe . This means that the redis string can contain any data. Such as jpg pictures or serialized objects.

    2.2String features

      1 . String type is redis most basic data structure , the first key is a string type, and several other structures are built on the basis of type string, so the string type can learn to respect the other four data structures Set the foundation .

      2. The string type can actually be a string (simple string, complex string (xml, json), number (integer, floating point), binary (picture, audio, video).

   2.3String application scenario     

         1.  Cache function : the most classic use case for strings, redis is the cache layer, Mysql is the storage layer , most of the request data is obtained from redis, because redis has the characteristics of supporting high concurrency, so the cache can usually speed up The role of writing and reducing back-end pressure.

          2. Counter : Many applications will use redis as the basic tool for counting , he can achieve the function of fast counting and query cache, and the data can be dropped to other data sources in one step. Such as: video playback number, the number of micro-blog comments, thumbs up, shares, the number of collections vibrato works, Jingdong sales of goods, the number of evaluation and so on . The system is to use redis as the basic component of the video playback count.

          3. Shared session : In cluster mode , in the case of few applications, it is generally sufficient to use the session replication function that comes with the container. When the application increases and the system is relatively complex, a session centered on memory databases such as Redis is generally built. Services, sessions are no longer managed by containers, but by session services and in-memory databases .  In this mode, as long as the high availability and scalability of redis are guaranteed, every time user update or query login information is obtained directly from redis .

          4 . Speed : For safety reasons, the phone allows users to enter a verification code every time you log in, in order not to short message interface is accessed frequently, it will limit the frequency of users to obtain a verification code every minute.

    2.4String commonly used commands 

01 set: used to set the value of the specified key, support to set the existing key
02 get: used to take the value of the specified key
03 setnx: used to set the value of the specified key, if the key already exists, it returns 0. nx stands for: not exist
04 setex: it is used to set the value for the specified key, and the effective time of the key needs to be specified. After 10 seconds, it returns null
05 setrange: re-cover the content for the specified key value, replace the content from the specified position in 4, and the final result is ming.
06 mset: set the value value corresponding to the key in batches, and set the username and age , Sex respectively correspond to wangwu, 10, 10
07 msetnx: set the value value corresponding to the key in batches, and return 0 if the key already exists. Because of the above settings, the result returns 0
08 getset: set a new value for the specified key, and return to the original data.
09 getrange: returns a substring of a string, which is equivalent to string interception, subscript 0 is the starting position, subscript 3 is the ending position
10 mget: get the value corresponding to the key in batches, show
11 incr: will specify The value of the number stored in the key is incremented by one, and it must be a numeric type, otherwise it will return an error message
11 incrby: increase the number stored in the specified key by

12decr: Decrease the numeric value stored in the specified key by one, it must be a numeric type, otherwise it will return an error message
13 decrby: Decrease the number stored in the specified key by how much
14 append: append the string
15 to the value in the specified key strlen: returns the length of the value in the specified key

3. Hash

   3.1 Introduction to Hash

     Redis hash is a collection of key / value pairs , similar to Map <String, Object> in Java,

      Redis hash is a mapping table of field and value of type string. Hash is particularly suitable for storing objects.

   3.2  Hash application scenarios

      The hash structure is more intuitive than the serialized cache information of the string, and it is more convenient in the update operation.

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

   3.3 Hash commands

      

. 1 .hset provided a hash value Field key, but can only set an attribute in the hash, if you want to set a plurality of bulk properties, you need to use the command hmset
 2 .hget Field key corresponding to the specified key acquired hash corresponding to the attribute values specified, each also can obtain a value corresponding to the attribute, if you want to obtain bulk property value, the need to use the command hmget
 . 3 .hmset Key Field value [(Field value) ...] provided a dispersion column, for example: name hmset key1 lonely Age 18 is , so that the catch will generate a hash key key1, the 
hash attribute name and there are two Age, the corresponding values are lonely and 18 is
. 4 .hmget key field ... returns the value corresponding to the specified key - name in the hash corresponding to the specified key . For example, based on the above example, the result of calling the hmget key1 name instruction is to obtain the value corresponding to the attribute name from the hash corresponding to key1 lonely is the result of a 5 .hdel key Field, Field, ... ... information delete the specified key corresponding hash specified. For example, key1: {name: Lonely, age: 25 }, then use the command hdel key1 age; result is deleted age attribute information, i.e. only key1: {name: Lonely} . 6Returns .hlen key corresponding to the hash key in the number of key-value pairs . 7 .hexists key field determines whether there is a key field attribute specified key corresponding to the hash

. 8 .hkeys Returns the key corresponding to the key hash key set, for example, there key1: {name: Lonely, Age: 25 }, then use the result hkeys key1 command name {,} Age . 9 .hvals hkeys with similar key command, but the command returns hvals hashes corresponding to the specified key the set value . 9 .hgetall key returns all the key information corresponding to the specified key 10 .hincrby Field increment the key corresponding to the specified key in hash value corresponding to the attribute specified increment increment units, note that only numeric values are only type Can take effect, return the incremental results

 4.List (list)

   4.1 Introduction to List

    Redis lists are simple lists of strings, sorted in order of insertion . You can add an element to the head (left) or tail (right) of the list. Its bottom layer is actually a linked list

    4.2 Features of List

      1. The list type is used to store multiple ordered strings , each string in the list becomes an element

        2. In redis , you can insert (pubsh) and pop (pop) at both ends of the queue list , you can also get the list of elements in the specified range, get the elements in the table under the specified index, etc.

        3. List is a relatively flexible data structure, it can act as a stack and queue, the list can store up to 232-1 elements (4294967295, each list can store more than 4 billion) .

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

  4.3 Application scenarios of List

     1. Message QueueRedis's lpush + brpop command combination can achieve a blocking queue. The producer client uses lupsh to insert elements from the left side of the list. Multiple consumer clients use the brpop command to block the "grab" of the list at the end Elements, multiple clients ensure consumer load balancing and high availability

       2. Article list : Each user has his own article list. Now it is necessary to display the article list in pages. At this time, you can consider using the list. The list is not only ordered but also supports obtaining elements according to the index range .

       3. The  latest list : The list type lpush command and lrange command can realize the function of the latest list . Each time a new element is inserted into the list through the lpush command, and then the latest element list is read through the lrange command, such as the likes of friends List, comment list.

      4.4Lsit common commands 

01 lpush: Add one or more elements to the head of the list, and return the number of elements in the current list, using the stack. 
02 lrange: Returns the elements in the specified interval in the list collection, 0 subscript represents the first element, -1 represents the last element.
03 rpush: Add one or more elements to the end of the list and return the number of elements in the current list, using a queue.
04 linsert: insert the element before or after the specified list element
05 lset: set the value of the subscript of the specified element in the list list, subscript 0 represents the first element, replaced by bear.
06 lrem: Delete the elements with the same n and value from the corresponding list. "Lrem list 1 noe" means to delete the elements with the same 1 and noe in the list. 07 LTRIM: key value data in the range specified in the reservation, there is a list of the known list of three elements, and now want to keep only the first two, the last display tow has been removed 08 lpop: remove an element from the head of the list, return deleted Element value.
09 rpop: Delete an element from the end of the list and return the deleted element value.
10 rpoplpush: Remove an element from the end of the first list and add it to the head of the second list. Remove an element from the end of the first list. The element at the end of mylist2 elephant, the rpop command does the second thing Add an element to the head of the list,
adding header elements of the list elephant, lpush command dry matter
. 11 the lindex: Returns the specified list subscripts element values, elements the subscript 0 Start
12 llen: Returns the number of elements in the list

   

 5.Set (set)

   5.1 Introduction to Set

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

    5 .2Set Features

         1. set is also used to save multiple string elements, but unlike the list, duplicate elements are not allowed in the set .

         2. The elements in the set are unordered, and the elements cannot be obtained by index subscript .

         3. In addition to supporting addition, deletion and modification of the collection, redis also supports multiple collections to take intersection, union and difference, and use the collection type reasonably, which can solve many practical problems in actual development.

     5.3set application scenarios

        1. Collection of friends / followers / fans / interested people : The unique feature of the set type makes it suitable for storing collections of friends / followers / fans / interested people . The number of elements in the collection may be many, and all are taken out each time The cost is not small. The set type provides some very useful commands for directly operating these sets. For example, the a. Sinter command can get the common friends of the two users A and B. The sismember command can determine whether A is a friend of B. c. The scard command can get the number of friends d. When following, the move command can transfer B from A's fan set to A's friend set

       2. Random display : The display area of ​​the app homepage is limited, but fixed content cannot always be displayed. One way is to first determine a batch of content that needs to be displayed, and then randomly obtain it from it, such as: Kugou music K song ring game There are a total of 29 hit songs, and 5 random shows on the home page; yesterday there are 200 hit songs and 30 random shows on the home page.

       3. Label (Tag ) : the SET collection type more typical usage scenarios , such as Yi users more interested in entertainment, sports, and another may be interested in the news, these interests is the label, with these data you can get the same label People, and users ’common hobbies, the interest labels that are often used on our blog sites, and users who have the same hobbies and pay attention to similar content use one label to merge them.

       4. Common friend function : common preferences, or can be extended to extended applications such as second-degree friends.

       5. Statistic website's independent IP : Using the uniqueness of the elements in the set collection, the independent IP of the website can be quickly counted in real time.

     6. blacklist single / whitelist : traffic often for reasons of safety, it requires the user blacklist, ip blacklist, blacklist equipment, SET type suitable data store blacklists, sismember command can be used to determine the user , Ip, whether the device is in the blacklist.

       7. Other applications : generating random numbers, such as lottery 

     4.4 Common commands of Set 

           

1 SADD key member1 [member2] Add one or more members to the collection
2 SCARD key Get the number of members of the collection 3 SDIFF key1 [key2] Returns the difference of all given collections
4 SDIFFSTORE destination key1 [key2] Returns the given collection of all collections Difference set and stored in destination
5 SINTER key1 [key2] returns the intersection of all given sets
6 SINTERSTORE destination key1 [key2] returns the intersection of all given sets and stores it in destination
7 SISMEMBER key member Determines whether the member element is the set key Member
8 SMEMBERS key returns all members in the collection
9 SMOVE source destination member moves the member element from the source collection to the destination collection
10 SPOP key removes and returns a random element in the collection
11 SRANDMEMBER key [count] returns one or Multiple random numbers
12 SREM key member1 [member2] removes one or more members from the set
13 SUNION key1 [key2] returns the union of all the given collections
14 SUNIONSTORE destination key1 [key2] the union of all the given collections is stored in the destination collection
15 SSCAN key cursor [MATCH pattern] [COUNT count] Iterate the elements in the collection

 6. ZSet (sorted set: ordered set)

     6.1 Introduction to ZSet

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

        Redis uses the score to sort the members of the set from small to large. The members of zset are unique, but the score can be repeated .

       6.2ZSet features

          ZSet retains the characteristic that the set cannot have duplicate members , but the difference is that the elements in the ordered set can be sorted , but the difference between it and the index index used as a sorting list is that it sets one for each element. Score, as a basis for sorting;

        6.3 ZSet application scenario

           1.  Leaderboards : orderly collection of classic usage scenarios , such as JD.com ’s daily mobile phone sales ranking, JD.com ’s monthly sales list, and new rankings of products by time . Video sites need to do rankings for videos uploaded by users Order maintenance may be many: according to time, in accordance with the amount of players, according to the number obtained by Chan et .

         6.4ZSet common commands   

1. ZADD key score1 member1 [score2 member2] Add one or more members to the ordered set, or update the score of the existing member
2 ZCARD key Get the number of members of the ordered set
3 ZCOUNT key min max calculation specified in the ordered set The number of members of the interval score
4 ZINCRBY key increment member In the ordered set, add the increment to the specified member's score
5 ZINTERSTORE destination numkeys key [key ...] Calculate the intersection of one or more ordered sets and The result set is stored in the new ordered set key
6 ZLEXCOUNT key min max Calculates the number of members in the specified dictionary interval in the ordered set
7 ZRANGE key start stop [WITHSCORES] returns the members in the specified interval of the ordered set through the index interval
8 ZRANGEBYLEX key min max [LIMIT offset count] returns the members of the ordered set through the dictionary interval
9 ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT] returns the members within the specified interval of the ordered set by score
10 ZRANK key member returns the specified member of the ordered set Index
11 ZREM key member [member ...] removes one or more members of the ordered set
12 ZREMRANGEBYLEX key min max removes all members of the given dictionary interval in the
ordered set
13 ZREMRANGEBYRANK key start stop removes the ordered set 14 ZREMRANGEBYSCORE key min max removes
all members of the given score interval in the ordered set 15 ZREVRANGE key start stop [WITHSCORES] returns the members in the specified interval in the ordered set, by index, score From high to low
16 ZREVRANGEBYSCORE key max min [WITHSCORES] returns the members in the specified score interval in the ordered set, the scores are sorted from high to low
17 ZREVRANK key member returns the ranking of the specified members in the ordered set, and the ordered set members decrease by the score (
Large to
small) Sort 18 ZSCORE key member returns the ordered set, the member's score value 19 ZUNIONSTORE destination numkeys key [key ...] Calculates the union of the given ordered set or sets, and stores it in the new the key in
20 ZScan key the Cursor [MATCH pattern] [COUNT COUNT] iterations ordered set of elements (including elements and elemental member )

Guess you like

Origin www.cnblogs.com/gzxg/p/12683603.html