16 common usage scenarios of Redis

1. Cache  

As Key-Value an in-memory database, Redis is the first application scenario that comes to mind as a data cache. It is very simple to use Redis to cache data. You only need to stringsave the serialized object through the type, but there are some points that need attention:

  •      It must be ensured that the keys of different objects will not be repeated, and the key should be as short as possible. Generally, the class name (table name) and the primary key are used to concatenate.
  •      It is also very important to choose an excellent serialization method, the purpose is to improve the efficiency of serialization and reduce memory usage
  •      There are generally two approaches to the consistency between the cache content and the database: 

               1: Only put the object into the cache after the database query. If the object is modified or deleted, the corresponding cache is directly cleared (or set to expire).

              2: After the database is added and queried, put the object into the cache, update the cache after modification, and clear the corresponding cache after deletion (or set it to expire).

2. Data sharing and distribution

String type, because Redis is a distributed independent service that can be shared among multiple applications

For example: Distributed Session

<dependency> 
 <groupId>org.springframework.session</groupId> 
 <artifactId>spring-session-data-redis</artifactId> 
</dependency>

3. Distributed lock

Nowadays, in a distributed environment, the single lock that comes with java is no longer applicable. Starting from Redis version 2.6.12, the set command of string adds some parameters:

EX : Set the expiration time of the key (in seconds)

PX : Set the expiration time of the key (in milliseconds)

NX : Set the key only if the key does not exist. SET key value NX is equivalent to SETNX key value 

XX : Set the key only if the key already exists.

Since this operation is atomic, a distributed lock can be implemented simply by this, for example:

  set lock_key locked NX EX 1 

       If this operation returns false , it means that the addition of the key is unsuccessful, that is, someone is currently occupying the lock. And if it returns true , it means that the lock is obtained, and the operation can be continued, and the lock is released through the del command after the operation. And even if the program does not release the lock for some reason, the lock will be automatically released after 1 second due to the set expiration time, which will not affect the operation of other programs.
 

4. Global ID

int type, incrby, using atomicity

incrby userid 1000

In the scene of sub-database and sub-table  , take one section at a time

5. Counter

int type, incr method

For example: the number of articles read, the number of Weibo likes , a certain delay is allowed, first write to Redis and then synchronize to the database at regular intervals

The counting function should be one of the most suitable usage scenarios for Redis, because its high-frequency read and write characteristics can fully utilize the efficiency of Redis as an in-memory database. In the data structure of Redis, string, hash, and sorted set all provide the incr method for atomic self-increment operations. The following examples illustrate their respective usage scenarios:

           1: If the application needs to display the number of registered users per day, it can use string as a counter, set a key named REGISTERED_COUNT_TODAY , and set an expiration time to 0:00 AM for it during initialization, every time the user registers successfully Use the incr command to increase the key by 1, and at the same time, after 0:00 every day, the counter will clear the value to zero because the key expires .
          2: Each microblog has four attributes: number of likes, number of comments, number of retweets, and number of views. At this time, it is better to use hash to count. The key of the counter is set to weibo:weibo_id, and the field of the hash is like_number, comment_number, forward_number and view_number , after the corresponding operation, the fields in the hash are auto-incremented through hincrby.
          3: If the application has a function of posting a leaderboard, select the sorted set and set the key of the set to POST_RANK. When a user posts a post, use zincrby to increase the score of the user id by 1 . The sorted set will be re-sorted, and the position of the user on the leaderboard will be updated in real time.
 

6. Current limiting

int type, incr method

Use the visitor's ip and other information as the key, increase the count once for each visit, and return false if the number exceeds

7. Bit Statistics 

Bitcount of String type (1.6.6 introduction to bitmap data structure)

Characters are stored in 8-bit binary

set k1 a
setbit k1 6 1
setbit k1 7 0
get k1 
/* 6 7 代表的a的二进制位的修改
a 对应的ASCII码是97,转换为二进制数据是01100001
b 对应的ASCII码是98,转换为二进制数据是01100010

因为bit非常节省空间(1 MB=8388608 bit),可以用来做大数据量的统计。
*/

8. Timeline

   listAs a doubly linked list, it can be used not only as a queue. If it is used as a stack, it can become a common time axis. After the user finishes posting the Weibo, lpushit is stored in a key LATEST_WEIBO, listand then lrangethe latest Weibo can be retrieved.

9. Message queue

       The data structure implementation of list in Redis is a doubly linked list, so it can be easily applied to message queues (producer/consumer model). The producer of the message only needs to put the message into the list through lpush, and the consumer can take out the message through rpop, and the order of the message can be guaranteed.

        If you need to implement a message queue with priority, you can also choose sorted set. And the pub/sub functionality can also be used as a publisher/subscriber model for messages. No matter which method is used, since Redis has a persistence function, there is no need to worry about message loss due to server failure.

List provides two blocking pop operations: blpop/brpop, timeout can be set

  • blpop: blpop key1 timeout removes and gets the first element of the list, if there is no element in the list, it will block the list until it waits for a timeout or finds a pop-up element.
  • brpop: brpop key1 timeout removes and gets the last element of the list, if there is no element in the list, it will block the list until it waits for a timeout or finds a pop-up element

operation above. In fact, it is java's blocking queue. The more things you learn. The lower the cost of learning

  • Queue: advanced and first divided: rpush blpop, head on the left and tail on the right, enter the queue on the right, and exit the queue on the left
  • Stack: first in last out: rpush brpop

10. Lucky Draw 

Using the disorder of the set structure, through Spop ( Redis Spop command is used to remove one or more random elements of the specified key in the collection, and the removed elements will be returned after removal.) Randomly obtain values

redis> SADD myset "one"
(integer) 1
redis> SADD myset "two"
(integer) 1
redis> SADD myset "three"
(integer) 1
redis> SPOP myset
"one"
redis> SMEMBERS myset
1) "three"
2) "two"
redis> SADD myset "four"
(integer) 1
redis> SADD myset "five"
(integer) 1
redis> SPOP myset 3
1) "five"
2) "four"
3) "two"
redis> SMEMBERS myset
1) "three"
redis> 

 11. Like, sign in, check in

Suppose the Weibo ID above is t1001, and the user ID is u3001

Use like:t1001 to maintain all users who like t1001's Weibo

Liked this Weibo : sadd like:t1001 u3001
Unliked :srem like:t1001 u3001
Liked :sismember like:t1001 u3001
All users who liked :smembers like:t1001
Number of likes :scard like:
t1001Yes Not much simpler than a database.

12 Product label 

As usual, use tags:i5001 to maintain all tags of the product.

  • sadd tags:i5001 The picture is clear and delicate
  • sadd tags: i5001 true color clear display
  • sadd tags: i5001 process to the extreme

13. Friend relationship, user attention, recommendation model

For a user A, store the user ids of its followers and fans in two sets:

A:follow: store all followed user ids of A

A:follower: store the user ids of all followers of A

Then through the sinter command, users who follow each other with A can be obtained according to the intersection of A:follow and A:follower. When A enters the homepage of another user B, the intersection of A:follow and B:follow is the joint focus of A and B, and the intersection of A:follow and B:follower means that the people A follows also follow B.

14. Leaderboard

Using sorted set (ordered set) and an algorithm to calculate popularity can easily create a popularity leaderboard, zrevrangebyscore can get the sequence in reverse order of scores, and zrank can get a member's position in the leaderboard (arranged in positive order of scores If you want to get the position in reverse order, you need to use zcard-zrank)

Add 1 to the number of news hits with id 6001:

zincrby hotNews:20190926 1 n6001

Get the 15 most clicked items today:

zrevrange hotNews:20190926 0 15 withscores

15. Inverted Index

Inverted index is the most common way to construct a search function. In Redis, an inverted index can also be established through set. Here is an example of a simple pinyin + prefix search function:

Assuming a city of Beijing, convert Beijing to beijing through the Pinyin thesaurus, and then divide the two words into several prefix indexes through prefix segmentation, including: Bei, Beijing, b, be...beijin and beijing. Use these indexes as the keys of the set (for example: index: north) and store the id of Beijing, and the inverted index is established. Next, you only need to take out the corresponding set and get the id in it through the keyword when searching.
 

16. Display the latest project list

For example, one of our web applications wants to list the last 20 comments posted by users. We have a "Show All" link next to the latest comments, which will take you to more comments.

Every time a new comment is published, we will add its ID to a Redis list. The length of the list can be limited to 5000

LPUSH latest.comments

In Redis we use a resident cache of the latest IDs, which is always updated. But we have made a limit of no more than 5000 IDs, so our get ID function will always ask Redis. Access to the database is only required when this range is exceeded.
 

Guess you like

Origin blog.csdn.net/XikYu/article/details/130098633