[Turn]redis usage scenarios for five types of data

Source: Internet
Author: User
Tags set set live chat

From:http://blog.csdn.net/gaogaoshan/article/details/41039581#t5

String [HTML]View Plaincopy
    1. 1, String
    2. Common commands:
    3. In addition to operations such as GET, set, INCR, Decr mget, Redis also provides the following actions:
    4. Get string length
    5. Append content to a string
    6. Set and get a section of a string
    7. Set and get one of the strings (bit)
    8. Bulk set the contents of a series of strings
    9. Application Scenarios:
    10. String is the most commonly used type of data, and ordinary key/value storage can be classified as such, and value is not only a string,
    11. It can also be a number: like to know when to block an IP address (access more than a few times). The Incrby command makes it easy to keep count by atomic increment.
    12. Implementation method:
    13. M,DECR and other operations will be converted into numerical type for calculation, at this time the Redisobject encoding field is int.
Hash [HTML]View Plaincopy
  1. Common commands:
  2. Hget,hset,hgetall and so on.
  3. Application Scenarios:
  4. Let's simply cite an example to describe the application scenario for a hash, such as storing a user information object data that contains the following information:
  5. User ID, the key for the lookup,
  6. The stored value User object contains the name name, age, birthday birthday, and other information,
  7. If you use a common key/value structure to store, there are 2 main storage methods:
  8. The first way is to use the user ID as a lookup key, to encapsulate other information as an object to be stored in a serialized way,
  9. such as: Set u001 "Lie triple, 18,20010101"
  10. The disadvantage of this approach is that the overhead of serialization/deserialization is increased, 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.
  11. The second method is how many members of this user information object will be saved into the number of key-value, with the user id+ the name of the corresponding property as a unique identifier to obtain the value of the corresponding property,
  12. such as: Mset User:001:name "Lie Triple" User:001:age18 User:001:birthday "20010101"
  13. Although the serialization overhead and concurrency issues are omitted, the user ID is a duplicate storage, and if there is a large amount of such data, the memory waste is very considerable.
  14. The hash provided by Redis is a good solution to this problem, and the Redis hash is actually the internal storage value for a hashmap,
  15. and provides a direct access to this map member's interface,
  16. Example: Hmset user:001 name "Lie Triple" Age Birthday "20010101"
  17. That is, the key is still user Id,value is a map, the map key is a member of the property name, value is the property value,
  18. This allows the data to be modified and accessed directly through its internal map key (Redis is called the internal Map key field), that is, by
  19. The key (User ID) + field (attribute tag) operation corresponds to the attribute data, which does not need to store the data repeatedly, nor does it bring up the problem of serialization and concurrency modification control. A good solution to the problem.
  20. It is also important to note that Redis provides an interface (Hgetall) that can fetch all of the property data directly, but if the internal map has a large number of members, it involves traversing the entire internal map, which can be time-consuming due to the Redis single-threaded model. The other client requests are not responding at all, which requires extra attention.
  21. Implementation method:
  22. The above has been said that the Redis hash corresponds to value inside the actual is a hashmap, actually there will be 2 different implementations, this hash of the members of the relatively small redis in order to save memory will be similar to a one-dimensional array to compact storage, without the use of a real HASHMAP structure , the encoding of the corresponding value Redisobject is Zipmap, and when the number of members increases, it automatically turns into a true hashmap, at which time encoding is HT.
List [HTML]View Plaincopy
  1. Common commands:
  2. Lpush,rpush,lpop,rpop,lrange,blpop (blocked version) and so on.
  3. Application Scenarios:
  4. Redis list has many applications and is one of the most important data structures for Redis.
  5. We can easily achieve the latest news ranking and other functions.
  6. Another application of the lists is Message Queuing, which can take advantage of the lists push operation to present the task in lists, and then the worker thread then takes the task out of execution with a pop operation.
  7. Implementation method:
  8. The implementation of Redis list is a doubly linked list, which can support reverse lookup and traversal, but it is more convenient to operate, but it brings some additional memory overhead, and many implementations within Redis, including sending buffer queues, are also used in this data structure.
  9. Rpoplpush Source Destination
  10. Command Rpoplpush performs the following two actions within an atomic time:
  11. POPs the last element in the list source (the trailing element) and returns it to the client.
  12. Inserts a source popup element into the list destination, as the head element of the destination list.
  13. If source and destination are the same, the footer elements in the list are moved to the table header and returned, which can be considered as a rotation (rotation) operation of the list.
  14. A typical example is the server's monitoring program: they need to check a set of Web sites in parallel, in the shortest possible time, to ensure their accessibility.
  15. Redis.lpush "Downstream_ips", "192.168.0.10"
  16. Redis.lpush "Downstream_ips", "192.168.0.11"
  17. Redis.lpush "Downstream_ips", "192.168.0.12"
  18. Redis.lpush "Downstream_ips", "192.168.0.13"
  19. Then:
  20. next_ip = Redis.rpoplpush "Downstream_ips", "Downstream_ips"
  21. Blpop
  22. Suppose there are three lists of job, command, and request, where the job does not exist, and both command and request hold a non-empty list. Consider the following command:
  23. Blpop Job command Request #阻塞30秒, 0 is blocked indefinitely, the job list is empty, is skipped, immediately after the command list of the first element is popped.
  24. 1) "Command" # the list to which the popup element belongs
  25. 2) "Update system ..." # The value that the popup element belongs to
  26. Why block versions of Pop, primarily to avoid polling. As a simple example, if we use list to implement a Task Force column. The thread that performs the task can invoke the blocked version of the pop to get the task so that the polling can be avoided to check for the presence of a task. The worker thread can return immediately when the task comes, or it can avoid the delay caused by polling.

Set [HTML]View Plaincopy
    1. 4. Set
    2. Common commands:
    3. Sadd,srem,spop,sdiff, Smembers,sunion and so on.
    4. Application Scenarios:
    5. The functionality provided by Redis set externally is a list-like feature, except that set is automatically weight-saving, and set is a good choice when you need to store a list of data and you don't want duplicate data. and set provides an important interface to determine whether a member is within a set set, which is not available in list.
    6. For example, in Weibo applications, everyone's friends have a collection (set), so that two people's common friend's operation, you may only need to use the intersection command.
    7. Redis also provides a set of intersection, set, and difference sets for the collection, which can be very convenient for real
    8. Implementation method:
    9. The internal implementation of set is a value that is always null hashmap, which is actually calculated by hashing the way to fast weight, which is also set to provide a judge whether a member is within the cause of the collection.


Sort Set [HTML]View Plaincopy
  1. 5. Sorted Set
  2. Common commands:
  3. Zadd,zrange,zrem,zcard, etc.
  4. Usage scenarios:
  5. A condition is a weight, such as the number of times the top is sorted.
  6. The Zrevrange command can be used to get the top 100 users according to the score, Zrank can be used to get the user rank, very straightforward and easy to operate.
  7. The usage scenario for Redis sorted set is similar to set, except that the set is not automatically ordered, and the sorted set can be ordered by the user with an additional priority (score) parameter, and is inserted in an orderly, automatic sort.
  8. For example, the public timeline of Twitter can be stored as score in the publication time, which is automatically sorted by time.
  9. For example: The class students sortedsets,value can be the student's school number, and score can be its test scores, so that the data into the collection, has been a natural sort.
  10. Also can use sorted sets to do with the weight of the queue, such as the normal message score is 1, the important message of the score is 2, and then the worker can choose to press score reverse order to get work tasks. Let important tasks take precedence.
  11. Applications that require precise setting of expiration time
  12. For example, you can set the score value of the sorted set to the timestamp of the expiration time, then you can simply sort through the expiration time, and periodically purge out-of-date data, not only to clear the expired data in Redis, You can think of this expiration time in Redis as an index to the data in the database, use Redis to find out what data needs to be deleted, and then delete the corresponding records from the database exactly.
  13. Implementation method:
  14. Redis sorted set internal use HashMap and jump Table (skiplist) to ensure the storage and ordering of data, HashMap in the member to score mapping, and the jumping table is all the members, sorted by HashMap in the score , the use of the structure of the jumping table can obtain a relatively high efficiency of finding, and it is relatively simple to implement.


Message Subscription [HTML]View Plaincopy
    1. 6, Pub/sub
    2. Pub/sub literally is the release (Publish) and Subscription (Subscribe), in Redis, you can set a key value for message publishing and message subscription,
    3. When a message is published on a key value, all clients subscribing to it receive the corresponding message. The most obvious use of this function is to use it as a real-time messaging system, such as regular live chat, group chat, and other functions.
    4. Client 1:subscribe Rain
    5. Client 2:publish Rain "My Love!!!"
    6. (integer) 2 indicates that several clients have subscribed to this message

Transaction [HTML]View Plaincopy
  1. 7, transactions
  2. Who says NoSQL does not support transactions, although Redis's transactions provides not strictly acid transactions (such as a string of commands executed with Exec execution, in the execution of the server down, then there will be a part of the command execution, the rest is not executed), However, this transactions provides the basic command package execution function (in case the server does not have a problem, you can ensure that a series of commands are executed together in sequence, there will be other client commands inserted to execute).
  3. Redis also provides a watch function, you can watch a key, and then execute transactions, in the process, if the value of this watched is modified, then this transactions will find and refuse to execute.
  4. Session 1
  5. (1) Step 1th
  6. Redis 127.0.0.1:6379> Get Age
  7. "10"
  8. Redis 127.0.0.1:6379> Watch Age
  9. Ok
  10. Redis 127.0.0.1:6379> Multi
  11. Ok
  12. Redis 127.0.0.1:6379>
  13. Session 2
  14. (2) Step 2nd
  15. Redis 127.0.0.1:6379> Set Age
  16. Ok
  17. Redis 127.0.0.1:6379> Get Age
  18. "30"
  19. Redis 127.0.0.1:6379>
  20. Session 1
  21. (3) Step 3rd
  22. Redis 127.0.0.1:6379> Set Age
  23. QUEUED
  24. Redis 127.0.0.1:6379> Exec
  25. (nil)
  26. Redis 127.0.0.1:6379> Get Age
  27. "30"
  28. Redis 127.0.0.1:6379>
  29. The first step, Session 1 has not been time to modify the value of age
  30. In the second step, Session 2 has set the age value to 30
  31. In the third step, session 1 wants to set the value of age to 20, but the result of an execution return is nil, stating that execution failed, and then we take the age value is 30, which is due to the optimistic lock on age in Session 1.

[Turn]redis usage scenarios for five types of data

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.