当前位置:网站首页>Ten common application scenarios of redis
Ten common application scenarios of redis
2022-07-25 14:24:00 【Work hard, work hard, gzc】
One 、 cache
As Key-Value Form of memory database ,Redis The first application scenario that will be thought of is as data cache . At present, this is a must kill technique used by almost all large and medium-sized websites , The proper use of caching can not only improve the speed of website access , It also greatly reduces database stress , While using Redis Caching data is also very simple , Just go through string type Save the serialized object , But there are some things to pay attention to :
( One ) Different objects must be guaranteed key No repetition , And make key Try to be as short as possible , Generally use the class name ( Table name ) It is spliced with a primary key .
( Two ) Choosing a good serialization method is also important , The purpose is to improve the efficiency of serialization and reduce memory consumption .
( 3、 ... and ) Consistency between cache content and database , There are generally two approaches here :
① Only put the object into the cache after the database query , If the object is modified or deleted , Directly clear the corresponding cache ( Or set to expire ).
② After adding and querying the database, put the object into the cache , Update cache after modification , Clear the corresponding cache after deletion ( Or set to expire ).
Two 、 Ranking List
Many websites currently have leaderboard applications , Such as the year of Taobao / Daily sales list 、 The new ranking of goods by time, etc . utilize Redis Of zset The structure can realize various complex leaderboard applications . For example, use zset And an algorithm to calculate the heat can easily create a heat ranking list ,zrevrangebyscore You can get the sequence in reverse order of fractions ,zrank You can get a member's position in the leaderboard ( Is the position when the fractions are arranged in positive order , If you want to get the position in reverse order, you need to use zcard-zrank).
3、 ... and 、 Counter
What is a counter , Such as the reading volume of the article 、 Microblog likes 、 The number of videos played on video websites, etc . In order to ensure that the data is effective , Every time you browse, you have to give +1, When the amount of concurrency is high, it is undoubtedly a challenge and pressure to request database operations every time . We can write Redis Then synchronize to the database regularly ,Redis Provided incr To implement the counter function , Memory operations , Very good performance , Great for these counting scenarios .
The counting function should be most suitable for Redis One of the usage scenarios of , Because its high-frequency reading and writing characteristics can be brought into full play Redis As an efficient memory database . stay Redis In the data structure of ,string、hash and sorted set provide incr Method is used for atomic self increasing operation , Here are some examples of their respective usage scenarios :
(1) If the application needs to display the number of registered users per day , You can use string As a counter , Set a name REGISTERED_COUNT_TODAY Of key, And set it to the early morning during initialization 0 The expiration time of the point , Every time the user registers successfully, it will use incr The command makes the key growth 1, At the same time every morning 0 After the point , Because of this key After expiration, the value is cleared .
(2) Every microblog has some likes 、 comments 、 Forwarding number and browsing number are four attributes , Use hash It would be better to count , Set the... Of this counter key Set to weibo:weibo_id,hash Of field by like_number、comment_number、forward_number and view_number, After the corresponding operation, pass hincrby send hash Medium field Self increasing .
(3) If the app has a function of posting leaderboards , choice sorted set More appropriate , Set the key Set to POST_RANK. When users post , Use zincrby Put the user id Of score growth 1.sorted set Will be reordered , The position of users in the leaderboard will be updated in real time .
Four 、 Current limiting
In some seckill activities , In an instant, there will be a large number of user requests pouring in , And probably the same user will constantly refresh the page or other operations to send a large number of requests , At this time, we can take current limiting measures . How to realize current limitation ? We can use Redis Of incr Method , With the visitor's ip And other information as key, Add one count at a time , When the number of visits of the same user exceeds our preset number, a prompt message will be returned ( For example, prompt the user to operate too frequently , Operate again after a certain time ).
5、 ... and 、 Distributed session
Cluster mode , In the case of few applications, it is generally used that the container comes with session Copy function can satisfy , When used in more and more complex systems , It's usually built to Redis And so on session service ,session No longer managed by containers , But by the session Service and memory database management .
6、 ... and 、 Distributed lock
Distributed technology is used in many Internet companies , The technical challenge of distributed technology is concurrent access to the same resource , Such as the overall situation ID、 Reduce inventory 、 Second kill and other scenes , The pessimistic lock of the database can be used in the scenario with small amount of concurrency 、 Optimistic lock to achieve , But in the case of high concurrency , It is not ideal to use database lock to control concurrent access of resources , Greatly affected the performance of the database . You can use Redis Of setnx Function to write distributed locks , If set, return to 1 Indicates that the lock is obtained successfully , Otherwise, the lock acquisition fails , There will be more details to consider in practical application .
stay Redis 2.6.12 Version start ,string Of set The command adds some parameters :
( One )EX: Set the expiration time of the key ( The unit is in seconds )
( Two )PX: Set the expiration time of the key ( The unit is millisecond )
( 3、 ... and )NX : Only if the bond doesn't exist , To set the key . SET key value NX The effect is equivalent to SETNX key value .
( Four )XX : Only if the bond already exists , To set the key .
Because this operation is atomic , You can simply implement a distributed lock , for example :
set lock_key locked NX EX 1
If this operation returns false, explain key Failed to add , That is, someone is currently occupying this lock . And if you go back true, It means you have the lock , Then you can continue the operation , And pass... After operation del Command to release the lock . And even if the program does not release the lock for some reason , Due to the expiration time , The lock will also be in 1 Automatically release in seconds , Will not affect the operation of other programs .
Here we recommend you to use redisson Third party libraries to implement distributed locks .
7、 ... and 、 Message queue
Message queue is a necessary middleware for large websites , Such as ActiveMQ、RabbitMQ、Kafka And other popular Message Queuing Middleware , It is mainly used for business decoupling 、 Peak shaving and asynchronous processing of low real-time services .Redis Provides a release / Subscription and blocking queue function , Can realize a simple message queue system .
in addition Redis in list The data structure implementation of is a two-way linked list , So it can be easily applied to message queue ( producer / Consumer model ). The producer of the message only needs to pass lpush Put the message into list, Consumers can use rpop Take out the message , And it can ensure the order of messages . If you need to implement message queuing with priority, you can also choose sorted set. and pub/sub Features can also be used as publishers / Subscriber model messages . No matter what method is used , because Redis With persistence , There is no need to worry about message loss due to server failure .
List Two blocked pop-up operations are provided :blpop/brpop, Timeout can be set :
blpop:blpop key1 timeout Remove and get the first element of the list , If there are no elements in the list, it will block the list until the wait timeout or pop-up elements are found .
brpop:brpop key1 timeout Remove and get the last element of the list , If there are no elements in the list, it will block the list until the wait timeout or pop-up elements are found .
The above operation is actually java Blocking queue
queue : First in, first out :rpush blpop, Left head right tail , Right into the queue , Queue left
Stack : First in, then out :rpush brpop
8、 ... and 、 Luck draw
utilize set Disorder of structure , adopt Spop( Redis Spop The command is used to remove the specified key One or more random elements of , After removal, the removed element will be returned . ) Random 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>
Nine 、 give the thumbs-up 、 Sign in
Suppose a user comments , We want to give him some praise , His ID yes t1001, user ID yes u3001.
Then we can use like:t1001 To maintain all like users of this comment .
// Like this Weibo
sadd like:t1001 u3001
// Cancel likes
srem like:t1001 u3001
// Do you like it
sismember like:t1001 u3001
// All users who like
smembers like:t1001
// Number of likes
scard like:t1001
This is not simpler than querying the database directly 、 More efficient ?
Ten 、 Show the latest list of projects
for instance , When we want to list the latest users on the web 20 comments , We have a... Next to the latest comment “ Show all ” Link to , Click to get more comments .
Redis List structure ,LPUSH You can insert a content in the head of the list ID As a keyword ,LTRIM Can be used to limit the number of lists , So the list is always N individual ID, No need to query the latest list , Direct basis ID Go to the corresponding content page .
That is, every time a new comment is published , We'll put it ID Add to a Redis list . You can limit the length of the list to 1000
LPUSH latest.comments
stay Redis Our latest ID Using resident cache , It's always updated . But we have made a limit not to exceed 1000 individual ID, So our acquisition ID The function will always ask Redis. Only when it goes beyond this range , To access the database .
边栏推荐
- 如何让一套代码完美适配各种屏幕?
- Xintang nuc980 set DHCP or static IP
- From fish eye to look around to multi task King bombing -- a review of Valeo's classic articles on visual depth estimation (from fisheyedistancenet to omnidet) (Part I)
- 新唐NUC980设置DHCP或者静态IP
- Four methods of importing CSV text files into Excel
- sqli-labs Basic Challenges Less1-10
- Easy entry natural language processing series 12 hidden Markov models
- IDEA设置提交SVN时忽略文件配置
- Save the image with gaussdb (for redis), and the recommended business can easily reduce the cost by 60%
- NUC980 设置SSH Xshell连接
猜你喜欢

~4.2 CCF 2021-12-1 sequence query

swiper 一侧或两侧露出一小部分

Typora cannot open the prompt to install a new version solution

元器件采购系统的主要功能,数字化采购助力元器件企业飞速发展

2271. Maximum number of white bricks covered by blanket ●●

基于PaddleOCR开发uni-app离线身份证识别插件

CDA level Ⅰ 2021 new version simulation question 1 (with answers)

手把手教你申请SSL证书
![einsum(): operands do not broadcast with remapped shapes [original->remapped]: [1, 144, 20, 17]->[1,](/img/bb/0fd0fdb7537090829f3d8df25aa59b.png)
einsum(): operands do not broadcast with remapped shapes [original->remapped]: [1, 144, 20, 17]->[1,

Realize a family security and environmental monitoring system (I)
随机推荐
Jqgrid select all cancel single line click cancel event
Reverse Integer
Xintang nuc980 set DHCP or static IP
Application practice: Great integrator of the paddy classification model [paddlehub, finetune, prompt]
Idea error failed to determine a suitable driver class
51单片机学习笔记(2)
苹果手机端同步不成功,退出登录,结果再也登录不了了
AI model risk assessment Part 1: motivation
jqgrid全选取消单行点击取消事件
Comprehensive sorting and summary of maskrcnn code structure process of target detection and segmentation
[cartographer_ros] VIII: Official demo parameter configuration and effect
CTS测试介绍(面试怎么介绍接口测试)
Pytorch training code writing skills, dataloader, Einstein logo
Typora无法打开提示安装新版本解决办法
[learning record] plt.show() solution to flash back
NAT/NAPT地址转换(内外网通信)技术详解【华为eNSP】
Resource not found: rgbd_launch 解决方案
Thymeleaf controls whether display is displayed through style
OverTheWire-Bandit
Goldfish rhca memoirs: cl210 managing storage -- managing shared file systems