Redis common usage scenarios

What is Redis?

Redis is a very fast open source non-relational, Key-Value database, a data structure commonly referred to as a server; it stores the key values ​​of five different types of mapping. As a database, caching and message broker.

One of the main differences between Redis Redis database, and other key data storage and advanced type of ability to operate. These data types are most developers are familiar with the basic data structures (lists, maps, sets and sorted sets). Redis of superior performance, simplicity of operation and the atomic data structures help solve the problem is difficult to achieve using traditional relational database or perform poorly.

Redis features

A product usage scenario certainly need to characteristics of the product, the first list what features Redis:

  • Good read and write performance
  • Endurance of
  • Rich data types
  • Single-threaded
  • Data is automatically expired
  • Publish and subscribe
  • distributed

Here we are a few scenarios, different dimensions of said application under the Redis.

Common scenarios

1, Cache

Redis cache is the most common scenarios, so use it all, mainly because of excellent Redis read and write performance. And there is a growing replace memcached, as the preferred server-side caching components. Moreover, the internal affairs of Redis is supported in the use of time can effectively ensure data consistency.

But there are caveats:

  • Must ensure that the key can not be reused in different objects, and the key to be short, the primary key using class names splicing.
  • Select an ordered sequence of way is also important aim is to improve efficiency and reduce serialization memory footprint.
  • During the data cache coherency. There are two general approaches:
    1. Only after the inquiry into the cache object database, if the object of the removal or modification operations, direct removal of the corresponding cache (or set to expire)
    2. New and placed in a database query after the object cache, the cache is updated after modify, delete clears the corresponding cache, or set to expire.

2, limit the use of business

redis expire command can be used to set the lifetime of a key, the time after redis will delete it. Using this feature can be used in limited-time promotions information, phone verification code and other business scenarios.

3, counter

Counting function should be one of the most suitable redis usage scenario, the reader high frequency characteristics can play redis as an efficient in-memory database. In the data structure of Redis, string, hash, and sorted set incr provides a method for atomic increment operation, illustrated below their respective scenarios:

  • If the application needs to display the number of registered users per day, it can be used Stringas a counter, set a named REGISTERED_COUNT_TODAYkey and give it a set expiration time to 0:00 at initialization, each time a user after successful registration using the incrcommand to make the key growth 1, while after 0:00 every day, this counter will expire because the key value is cleared.
  • Each micro-blog are a bit like the number of comments, number of forwarding and Views four properties, which is hashcounting will be better, the key counter is set weibo:weibo_id, hashthe field for the like_number, comment_number, forward_numberand view_number, after the corresponding operation by hincrbyso that hash 中the field increment.
  • If the application has posted a list of the function, then select sorted setit, key to the collection POST_RANK. When users post, using zincrbythe user id's score increased 1. sorted setWill re-sort the list of the user's position will also get real-time updates.

4, leaderboard

Use sortedset can easily create a fever chart, zrevrangebyscore can get a sequence of scores in reverse order, zrank can get the role of members in the chart.

5, distributed lock

In Redis2.6.12 version, stringthe set command added three parameters:

  • Ex: A setting key expiration time (s)

  • Px: Setting key expiration time (ms)

  • NX| XX: When set NX, the key is present only when it is operated, is set to xx, only when the key is not present will be operated, this operation is atomic, a distributed lock can be simply realized, for example:

    set key "lock" Ex 1 xx
    

    If the operation returns false, key explanation of unsuccessful added that it was currently occupied by the lock, and if it returns true, explanation has been locked, it can continue to operate after the operation through delout the lock is released, and even if for some reason there is no program release the lock, set an expiration time, so the lock will be automatically released in 1 second.

  • Fake code:

    //产生锁
    while lock!=1
        //过期时间是为了避免死锁
        now = int(time.time())
        lock_timeout = now + LOCK_TIMEOUT + 1
        lock = redis_client.setnx(lock_key, lock_timeout)
    
    //真正要处理的业务
    doing() 
    
    //释放锁
    now = int(time.time())
    if now < lock_timeout:
        redis_client.delete(lock_key)
    

     

6, delay in operation

For example, when we take up the inventory-to-order, 10 minutes to test the user is really enough to buy, do not buy if the document set is invalid, while reducing inventory. Since redis since the 2.8.0 version provides Keyspace Notifications feature that allows customers to subscribe to Pub / Sub Channel, Redis data set in order to receive event influence in some way. So we For the above needs can use the following solutions, we are in the order, set a key, and set 10 minutes expired, we implement a listener in the background, monitoring key effectiveness, listening to the follow-up when the key failure plus logic. Of course, we can also use rabbitmq, activemq such as messaging middleware delay queue service to meet the requirement.

7, paging, fuzzy search

redis collection set in a zrangebylex method provides the following syntax:

ZRANGEBYLEX key min max [LIMIT offset count]

Can collate data inquiry + LIMIT 0 10, wherein - - represents ZRANGEBYLEX zset + by acquiring all the data

zrangebylex key min max that can return data dictionary intervals, use of this feature can be fuzzy query function, I found that this is currently the only one in redis support features for store content fuzzy queries.

8, thumbs up, buddy relationship, etc.

An introduction PPT microblogging Redis application, which refers to microblogging Redis is mainly used in both the count and friendship,

"Redis Design and Implementation" in the beginning of the use Redis setis because traditional databases can not be calculated intersection of the sets.

For a user A, and fans will be its focus on user id are stored in two set:

  • A:follow: A store all user id's attention

  • A:follower: Store the user id A all fans

    By then sinterit can command A:followand A:followerget user A is interested in the intersection of each other. When A enters the home of another user B, A:followand B:followthe intersection is the common focus of A and B, A:followand B:followerthe intersection of person A is also concerned about the concern B.

9, queue

Redis of lista data structure of the doubly linked list is implemented, it can be very easily in the message queue (producer / consumer model). Message producer only need to put a message lpush list, the message can be removed by the consumer rpop, and ensure orderly message.

If you want a message queue with priority may be selected ** sorted list. Andpub/sub ** can be used as a message publisher / subscriber model. Since Redis with persistence function, without worrying about server failure lead to message loss occurs.

10, timeline

list as a doubly linked list, not only can be used as a queue, if it is used as the stack can become a common timeline. When the user finishes made to it, through lpush it is stored in a key LATEST_WEIBO the list. It can be removed after the latest micro-blog by lrange.

11, inverted index

Inverted index is the most common way to structure search function, Redis can also be inverted index established by the set, here's a simple example phonetic search prefix + urban functions:

Suppose a city 北京by spelling dictionary will 北京turn beijing, and then the prefix word by these two words are divided into a number prefix index, are: , 北京, b, be... beijinand beijing. These indexes were used as setkey (for example: a index:北) and store 北京the id, the inverted index will be established as well. Next, remove only the corresponding keyword in the search set, and can be obtained in which the id.

 

Example: Binding of spike and Redis

Spike is now common in the Internet marketing model system, as a developer, in fact, most do not want such an event, because non-technical personnel can not understand the technical difficulties which led always some bias in resource coordination. In fact, spike problems often occur include:

  • Concurrent too high causing the program to blocking.
  • Inventory can not be effectively controlled, the situation appears oversold.

In fact, solve these problems basically two options:

  • Try to cache data, and blocking direct user interaction database.
  • By controlling the lock avoid oversold.

Now explain that if we make a spike, then, Redis should be how to combine the use?

  • Warm-up ahead of data, add Redis
  • Product List into Redis List
  • Details Product Data Redis hash save, set an expiration time
  • Inventory data Redis sorted set of stored goods
  • Redis set user address information hold
  • Buckle-stock orders generated by the distributed lock Redis, inventory synchronization deduction
  • After the order shipment data generated, generates Redis list, by the message queue processing
  • After the spike, and then synchronize data and databases Redis

The above is a brief spike systems and Redis combination of programs, of course, may also introduce actual http cache, or docking with MQ messages instead of other programs, the business case will also appear missing, this is just hoping to start a discussion.

Published 109 original articles · won praise 101 · views 360 000 +

Guess you like

Origin blog.csdn.net/Alen_xiaoxin/article/details/105147833