当前位置:网站首页>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 .
边栏推荐
- 苹果官网产品打折 买iPhone 13 Pro Max 可省600元
- pt100测温电路图(ad590典型的测温电路)
- Initial flask and simple application
- [directory blasting tool] information collection stage: robots.txt, Yujian, dirsearch, dirb, gobuster
- How to design a high concurrency system?
- CDA level Ⅰ 2021 new version simulation question 2 (with answers)
- Deep understanding of pytorch distributed parallel processing tool DDP -- starting from bugs in engineering practice
- Resource not found: rgbd_launch 解决方案
- Matplotlib data visualization three minutes entry, half an hour enchanted?
- sqli-labs Basic Challenges Less1-10
猜你喜欢

Word set paste to retain only text

Why do China Construction and China Railway need this certificate? What is the reason?

依迅总经理孙峰:公司已完成股改,准备IPO

sqli-labs Basic Challenges Less11-22

Deep understanding of pytorch distributed parallel processing tool DDP -- starting from bugs in engineering practice

Mongodb source code deployment and configuration

Realsense-Ros安装配置介绍与问题解决

The security market has entered a trillion era, and the security B2B online mall platform has been accurately connected to deepen the enterprise development path

如何设计一个高并发系统?

实现一个家庭安防与环境监测系统(一)
随机推荐
The practice of depth estimation self-monitoring model monodepth2 in its own data set -- single card / multi card training, reasoning, onnx transformation and quantitative index evaluation
Opencv video tracking "suggestions collection"
sqli-labs Basic Challenges Less1-10
filters获取data中的数据;filters使用data中的数据
苹果手机端同步不成功,退出登录,结果再也登录不了
PS making and loading GIF pictures tutorial
Typora无法打开提示安装新版本解决办法
Doris学习笔记之与其他系统集成
Depth estimation self-monitoring model monodepth2 paper summary and source code analysis [theoretical part]
~5 new solution of CCF 2021-12-2 sequence query
bond0脚本
疫情之下,生物医药行业或将迎来突破性发展
2271. Maximum number of white bricks covered by blanket ●●
It is predicted that 2021 will accelerate the achievement of super automation beyond RPA
关于ROS2安装connext RMW的进度条卡在13%问题的解决办法
Under the epidemic, the biomedical industry may usher in breakthrough development
sudo rosdep init Error ROS安装问题解决方案
Detailed explanation of how R language converts large Excel files into DTA format
opencv视频跟踪「建议收藏」
金鱼哥RHCA回忆录:CL210管理存储--对象存储