Redis usage scenarios for each data type [organize]

Source: Internet
Author: User
Tags ranges live chat

Redis supports five types of data: string (String), hash (hash), list, set (set), and Zset (sorted set: Ordered set).

Redis List command

Reference: http://www.redis.net.cn/tutorial/3501.html

Use scene string

The string data structure is a simple key-value type, and value can actually be not only a string, but also a number.
General Key-value cache Application;
Regular count: Number of Weibo, number of fans, etc.

Hash

Redis Hash is a string-type field and value mapping table, and hash is particularly useful for storing objects.
Store part of the changed data, such as user information.

List

Lists are linked lists, and people with a slight knowledge of data structures should be able to understand their structure. With the lists structure, we can easily achieve the latest message ranking and other functions. Another application of list is the message queue, which can take advantage of the push operation of list, the task exists in list, and then the worker thread takes out the task with the pop operation to execute. Redis also provides an API to manipulate a section of the list, and you can query directly to remove elements from a section of the list.
The Redis list is a doubly linked list with each child element being a string type, which can be added or removed from the head or tail of the list via push and pop operations, so that the list can be used as a stack or as a queue.

Message Queuing System
Using list, you can build a queue system, and you can even build a prioritized queue system using sorted set.
For example, use Redis as the log collector
is actually a queue, multiple endpoints write log information to Redis, and a worker uniformly writes all logs to disk.

Operations that take the latest n data

//把当前登录人添加到链表里ret = r.lpush("login:last_login_times", uid)//保持链表只有N位ret = redis.ltrim("login:last_login_times"0, N-1)//获得前N个最新登陆的用户Id列表last_login_list = r.lrange("login:last_login_times"0, N-1)

such as Sina Weibo:
Our latest Weibo ID in Redis uses a resident cache, which is always updated. But the limit does not exceed 5,000 IDs, so the function that gets the ID will always ask for Redis. Access to the database is required only if the Start/count parameter is out of range.
The system does not "refresh" the cache in the traditional way, and the information in the Redis instance is always consistent. The SQL database (or other type of database on the hard disk) is only triggered when the user needs to get "very far" data, and the home page or the first comment page will not bother the database on the hard disk.

Set

A set is a set, and the concept of a collection is a combination of a bunch of distinct values. Using the set data structure provided by Redis, you can store some aggregated data. The elements in the set are not sequential.
Case:
In a microblog app, you can have a collection of all the followers of a user, and a collection of all of their fans. Redis also provides for the collection of intersection, set, difference sets and other operations, can be very convenient to achieve such as common concern, common preferences, two-degree friends and other functions, to all of the above collection operations, you can also use different commands to choose whether to return the results to the client or save set into a new collection.

Intersection, and set, difference set

//book Table store book nameSetBook1: Name"The Ruby programming Language"SetBook2: Name"Ruby on Rail"SetBook3: Name"Programming Erlang"//tag tables use collections to store data because the collection is adept at intersection, setSaddTag: Ruby1SaddTag: Ruby2SaddTag: Web2SaddTag: Erlang3//a book that belongs to Ruby and is a Web? Inter_list=Redis.Sinter"Tag:web","Tag:ruby")//Is it a book that belongs to Ruby but does not belong to the Web? Diff_list=Redis.Sdiff ("Tag:ruby","Tag:web")//A collection of books that belong to Ruby and belong to the Web? Union_list=Redis.Sunion ("Tag:ruby","Tag:web")

get all data deduplication for a certain period of time
This is the most appropriate set data structure to use Redis, just to constantly throw it into set, set means set, so it automatically takes weight.

Sorted set

Compared with set, sorted set added a weight parameter score, so that the elements in the collection can be ordered by score, such as a storage class sorted set, the collection value can be the student's school number, and score can be its test scores, This allows the data to be sorted in a natural way when it is inserted into the collection. You can use sorted set to make a queue with weights, such as the score of the normal message is 1, the important message score is 2, and the worker thread can choose to get the work task in reverse order of score. Let important tasks take precedence.

leaderboard Application, Top n operation
This requirement differs from the above requirements in that the preceding operation takes the time as the weight, this is the weight of a certain condition, such as the number of times by the top, then we need our sorted set to go, set the value you want to sort into the score of sorted set, Set the specific data to the corresponding value, each time only need to execute a zadd command.

set511223//当用户登录时,对该用户的登录次数自增1ret = r.zincrby("login:login_times"1, uid)//那么如何获得登录次数最多的用户呢,逆序排列取得排名前N的用户ret = r.zrevrange("login:login_times"0, N-1)

For example, online game leaderboards, depending on the score you usually want to:

     - 列出前100名高分选手     - 列出某用户当前的全球排名

These operations are a piece of cake for redis, and even if you have millions of users, there will be millions of new points per minute.
The pattern is this, each time we get a new score, we use this code:

<score><username>

You may replace username with a userid, depending on how you designed it.
Getting the top 100 high-score users is simple:

ZREVRANGE leaderboard 0 99

The global rankings for users are similar, and only need to:

<username>

applications that require precise setting of expiration time
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.

Range Lookup
A question from Redis on Google Group, a classmate to ask for help, said to solve the following problem: He has an IP range corresponding to the list of addresses, now need to give an IP case, quickly find the IP in which range, that is, to determine the IP of all the ground. The question drew the answer from Redis author Salvatore Sanfilippo (@antirez). The answers are as follows:
For example, there are two ranges, 10-20 and 30-40
-A_start, A_end 20
-B_start, B_end 40
We will have the starting position of these two ranges in the sorted set data structure of Redis, the base range starting value as score, the range name plus start and end for its value:

Redis127. 0. 0. 1: 6379>Zadd Ranges10A_start1Redis127. 0. 0. 1: 6379>Zadd Ranges20A_end1Redis127. 0. 0. 1: 6379>Zadd Ranges30B_start1Redis127. 0. 0. 1: 6379>Zadd Ranges40B_end1

The data is then inserted into the sorted set, which is equivalent to arranging the starting positions in order.
Now I need to find out where the value of 15 is in the range, only the following zrangbyscore lookups are required:

redis127.0.0.1:6379> zrangebyscore ranges (15011"A_end"

This command means finding the first value greater than 15 in the sorted sets. (+inf represents positive infinity in Redis, and 15 front brackets denote >15 rather than >=15)
The result of the lookup is a_end, since all values are in order, so it is possible to determine that 15 is on the A_start to A_end interval, that is, 15 is in a range. That's it.
Of course, if you find a start, like we use 25, execute the following command:

redis127.0.0.1:6379> zrangebyscore ranges (25011"B_start"

The return result indicates that the next node is a start node, meaning that the value of 25 is not in any range between start and end.
Of course, this example applies only to cases similar to the IP range lookups above, because there is no overlap between the ranges of values. If there is a coincidence, the problem itself becomes a one-to-many problem.

Pub/sub

Pub/sub literally is the release (Publish) and Subscription (Subscribe), in Redis, you can set a key value for message publishing and message subscription, when a key value on a message published, all subscribed to its client will 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.

Usage Scenarios

Pub/sub Building a real-time messaging system

Redis's pub/sub system can build a real-time messaging system
For example, many real-time chat systems built with Pub/sub.

Reference:
Http://www.redis.net.cn/tutorial/3501.html
Http://www.cnblogs.com/markhe/p/5689356.html
Http://www.cnblogs.com/ggjucheng/p/3349102.html

Redis usage scenarios for each data type [organize]

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.