The usage scenarios of the five data types of redis

String
   
1、String  
    Common commands:  
    In addition to get, set, incr, decr mget and other operations, Redis also provides the following operations:  
    get string length  
    append content to string  
    Set and get a section of a string  
    Set and get a bit of a string  
    Batch set the contents of a series of strings  
      
    Application scenarios:  
    String is the most commonly used data type, ordinary key/value storage can be classified into this category, value is not only String,  
    Can also be numbers: like wanting to know when to block an IP address (access more than a few times). The INCRBY command makes this easy, keeping counts by atomically incrementing them.  
      
    Method to realize:  
    m, decr and other operations will be converted to numeric type for calculation, at this time, the encoding field of redisObject is int.  

Hash
   
Common commands:  
    hget,hset,hgetall 等。  
    Application scenarios:  
    Let's take a simple example to describe the application scenario of Hash. For example, we want to store a user information object data, including the following information:  
               User ID, which is the key to look up,  
               The stored value user object contains information such as name, age, birthday, etc.  
       If you use the ordinary key/value structure to store, there are mainly the following two storage methods:  
           The first method uses the user ID as the search key, and encapsulates other information into an object and stores it in a serialized manner.  
               Such as: set u001 "Li San,18,20010101"  
               The disadvantage of this method is that it increases the overhead of serialization/deserialization, and when one of the information needs to be modified, the entire object needs to be retrieved, and the modification operation needs to protect concurrency and introduce complex problems such as CAS.  
           The second method is to store as many key-value pairs as the user information object has as many members, and use the user ID + the name of the corresponding attribute as the unique identifier to obtain the value of the corresponding attribute.  
               如:mset user:001:name "李三 "user:001:age18 user:001:birthday "20010101"  
               Although serialization overhead and concurrency problems are eliminated, the user ID is stored repeatedly. If there is a large amount of such data, the memory waste is still considerable.  
        Then the Hash provided by Redis solves this problem very well. The Hash of Redis is actually a HashMap where the value stored internally is a HashMap.  
        And provides an interface to directly access this Map member,  
            如:hmset user:001 name "李三" age 18 birthday "20010101"     
                That is to say, the Key is still the user ID, the value is a Map, the key of this Map is the attribute name of the member, and the value is the attribute value.  
                In this way, the modification and access of data can be directly passed through the key of its internal map (in Redis, the key of the internal map is called field), that is, through   
                The key (user ID) + field (attribute label) operation corresponds to the attribute data, which neither needs to store the data repeatedly nor brings about the problems of serialization and concurrent modification control. Great solution to the problem.  
      
              At the same time, it should be noted that Redis provides an interface (hgetall) that can directly get all attribute data, but if there are many members of the internal map, it involves the operation of traversing the entire internal map. Due to the single-threaded model of Redis, this traversal operation It may be time-consuming, and the requests of other clients do not respond at all, which requires special attention.  
      Method to realize:  
        As mentioned above, Redis Hash corresponding to Value is actually a HashMap. In fact, there will be two different implementations. When there are few members of this Hash, Redis will use a one-dimensional array-like method for compact storage in order to save memory, instead of using real HashMap structure, the encoding of the corresponding value redisObject is zipmap, when the number of members increases, it will be automatically converted into a real HashMap, at this time the encoding is ht.
 
List
   
Common commands:  
        lpush, rpush, lpop, rpop, lrange, BLPOP (blocking version), etc.  
      
    Application scenarios:  
        There are many application scenarios of Redis list, and it is also one of the most important data structures of Redis.  
        We can easily implement the latest news ranking and other functions.  
        Another application of Lists is the message queue. You can use the PUSH operation of Lists to store tasks in Lists, and then the worker thread uses the POP operation to fetch the tasks for execution.  
      
    Method to realize:  
        The implementation of Redis list is a doubly linked list, which can support reverse search and traversal, which is more convenient to operate, but brings some additional memory overhead. Many internal implementations of Redis, including sending buffer queues, also use this data structure.  
      
    RPOPLPUSH source destination  
      
        The command RPOPLPUSH performs the following two actions in an atomic time:  
        Pops the last element (tail element) in the list source and returns it to the client.  
        Insert the element popped by source into the list destination as the head element of the destination list.  
        If source and destination are the same, the element at the end of the list is moved to the head, and that element is returned. This special case can be thought of as a rotation operation of the list.  
        A typical example is server monitoring programs: they need to check a group of websites in parallel to ensure their accessibility in the shortest possible time.  
        redis.lpush "downstream_ips", "192.168.0.10"  
        redis.lpush "downstream_ips", "192.168.0.11"  
        redis.lpush "downstream_ips", "192.168.0.12"  
        redis.lpush "downstream_ips", "192.168.0.13"  
        Then:  
        next_ip = redis.rpoplpush "downstream_ips", "downstream_ips"  
      
    BLPOP  
      
      Suppose there are now three lists of job, command and request, of which job does not exist, and both command and request hold non-empty lists. Consider the following command:  
      BLPOP job command request 30 #Block for 30 seconds, 0 means blocking indefinitely, the job list is empty, it is skipped, and then the first element of the command list is popped up.  
      1) "command" # Pop up the list to which the element belongs  
      2) "update system..." # popup the value to which the element belongs   
      Why block the version of pop, mainly to avoid polling. As a simple example if we use list to implement a work queue. The thread executing the task can call the blocking version of pop to get the task and thus avoid polling to check if a task exists. When the task comes, the worker thread can return immediately, and it can also avoid the delay caused by polling.  

Set
  
4、Set  
      
    Common commands:  
        sadd, srem, spop, sdiff, smembers, sunion 等。  
      
    Application scenarios:  
        The function provided by Redis set to the outside world is similar to that of list, which is a list function. The special feature is that set can automatically arrange weights. When you need to store a list of data and do not want duplicate data, set is a good choice. , and set provides an important interface for judging whether a member is in a set collection, which is also not provided by list.  
        For example, in the Weibo application, each person's friends are stored in a set, so the operation of asking for the common friends of two people may only need to use the request for intersection command.  
        Redis also provides operations such as intersection, union, and difference for sets, which can be very convenient to implement.  
      
    Method to realize:  
        The internal implementation of set is a HashMap whose value is always null. In fact, it is used to quickly arrange weights by calculating the hash. This is why set can provide judgment whether a member is in the set.  

Sort Set
  
5、Sorted set  
      
      Common commands:  
        zadd,zrange,zrem,zcard等  
      
      scenes to be used:  
        Take a certain condition as a weight, such as sorting by the number of tops.  
        The ZREVRANGE command can be used to get the top 100 users according to their scores, and ZRANK can be used to get the user ranking, which is very direct and easy to operate.  
        The usage scenario of Redis sorted set is similar to that of set, the difference is that set is not automatically sorted, while sorted set can sort members by providing an additional priority (score) parameter by the user, and it is inserted in order, that is, automatic sorting .  
        For example, the public timeline of twitter can be stored with the publication time as the score, so that it is automatically sorted by time when it is acquired.  
        For example, in the SortedSets of the scores of the whole class, the value can be the student number of the classmate, and the score can be the score of the test, so that the data is inserted into the set, and the natural sorting has been carried out.  
        In addition, Sorted Sets can be used as a weighted queue. For example, the score of ordinary messages is 1, and the score of important messages is 2. Then the worker thread can choose to obtain work tasks in reverse order of score. Prioritize important tasks.  
      
        Applications that need to accurately set the expiration time  
        For example, you can set the score value of the sorted set mentioned above to the timestamp of the expiration time, then you can simply sort by the expiration time and clear the expired data regularly, not only to clear the expired data in Redis, you can completely The expiration time in Redis is used as an index for the data in the database. Redis is used to find out which data needs to be expired and deleted, and then accurately delete the corresponding records from the database.  
      
      
      Method to realize:  
        The interior of Redis sorted set uses HashMap and SkipList to ensure the storage and ordering of data. HashMap stores the mapping from members to scores, and the skip list stores all members. The sorting is based on the storage in HashMap. The score, using the structure of the jump table can obtain relatively high search efficiency, and is relatively simple in implementation.  

News subscription
6、 Pub/Sub  
  
    Pub/Sub literally means Publish and Subscribe. In Redis, you can set message publishing and message subscription for a certain key value.  
    When a message is published on a key value, all clients that subscribe to it will receive the corresponding message. The most obvious usage of this function is as a real-time messaging system, such as ordinary instant chat, group chat and other functions.  
  
Client 1: subscribe rain  
Client 2: PUBLISH rain "my love!!!"  
    (integer) 2 means how many clients subscribe to this message  

transaction
7、Transactions 
 
   
Who said that NoSQL does not support transactions, although Redis's Transactions does not provide strict ACID transactions (such as a series of commands submitted and executed with EXEC, and the server is down during execution, then some commands will be executed, and the rest will be executed. Not executed), but this Transactions still provides the function of basic command packaging and execution (if there is no problem with the server, it can ensure that a series of commands are executed together in sequence, and there will be other client commands inserted in the middle. implement).  
    Redis also provides a Watch function. You can watch a key and then execute Transactions. During this process, if the value of Watched is modified, the Transactions will find and refuse to execute.  
Session 1  
    (1) Step 1  
    redis 127.0.0.1:6379> get age  
    "10"  
    redis 127.0.0.1:6379> watch age  
    OK  
    redis 127.0.0.1:6379> multi  
    OK  
    redis 127.0.0.1:6379>  
   
Session 2  
    (2) Step 2  
    redis 127.0.0.1:6379> set age 30  
    OK  
    redis 127.0.0.1:6379> get age  
    "30"  
    redis 127.0.0.1:6379>  
  
Session 1     
    (3) Step 3  
    redis 127.0.0.1:6379> set age 20  
    QUEUED  
    redis 127.0.0.1:6379> exec  
    (nil)  
    redis 127.0.0.1:6379> get age  
    "30"  
    redis 127.0.0.1:6379>  
  
    The first step, Session 1 has not had time to modify the value of age  
  In the second step, Session 2 has set the value of age to 30  
  In the third step, Session 1 wants to set the value of age to 20, but the result is nil when executed, indicating that the execution failed, and then we take the value of age to 30. This is because Session 1 adds an optimistic lock to age. caused.



Source: http://blog.csdn.net/gaogaoshan/article/details/41039581/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326435835&siteId=291194637