当前位置:网站首页>10 "no no no" redis interview questions
10 "no no no" redis interview questions
2022-06-22 04:47:00 【Bug trendsetter】
Here are Redis Interview questions , I believe everyone will feel familiar and strange 、 I've seen it. I may forget it immediately after a short interview .JavaPub Sort out these easily forgotten key knowledge and answer , Recommended collection , Review and consult often .
See the comments section
@
1. Redis What is it? ?
2. What scenarios do you use redis
3. Why? Redis It's single threaded ?
4. Redis There are several ways to persist ?
5. What is cache penetration ? How to solve ?
6. What is a cache avalanche ?
7. Redis How to optimize memory in use ?
8. You redis Which deployment method to use ?
9. redis What should we pay attention to when implementing distributed locks ?
1. Redis What is it? ?
Generally speaking, you should answer the following questions at least , If you don't know the basics , Recommended reading 《 rodert Single row learning redis》
Redis It's a Memory based key-value The storage system , The data structure includes character string 、list、set、zset(sorted set -- Ordered set ) and hash,bitmap,GeoHash( coordinate ),HyperLogLog,Streams(5.x After the version )
2. What scenarios do you use redis
You have practical experience , Then go straight to the show . without , Select some of the following classic scenes
Use as a queue ,( Because it's memory based 、 Generally, it will not be used as a consumption queue 、 As a circular queue, it is necessary to apply );
The simulation is similar to token This kind of scenario needs to set the expiration time , Login failure ;
Distributed cache , Avoid a large number of requests to the underlying relational database , Greatly reduce database pressure ;
Distributed lock ;
be based on bitmap Implement the bloon filter ;
Ranking List - be based on zset( Ordered collection data types );
Counter - For views 、 The playback volume is high , Use redis incr Realize the counter function ;
Distributed session ;
The messaging system ;
3. Why? Redis It's single threaded ?
This question gives an official answer
because Redis Is a memory based operation ,CPU No Redis Bottleneck ,Redis The most likely bottleneck is the size of machine memory or network bandwidth . Since a single thread is easy to implement , and CPU Not a bottleneck , So it's natural to adopt a single thread solution .
4. Redis There are several ways to persist ?
redis There are two ways to persist , Namely Snapshot mode (RDB Redis DataBase) And file appending (AOF Append Only File).
Obvious , Snapshot restart recovery is fast 、 But data is more likely to be lost , The data appended to the file is more complete 、 Slow restart recovery .
Mixed persistence ,Redis 4.0 And then the new way , Hybrid persistence is a combination of RDB and AOF The advantages of , When writing, first put the current data in RDB Is written to the beginning of the file , Then, the following operations are represented by AOF In the file , This will ensure the speed of restart , And reduce the risk of data loss .
On recovery , Restore the files saved in snapshot mode first , Then restore the incremental data in the appended file .
5. What is cache penetration ? How to solve ?
Cache penetration refers to that the data requested by the user does not exist in the cache, that is, there is no hit , And it doesn't exist in the database , As a result, every time the user requests the data, he / she has to query the database again , Then return to empty .
If a malicious attacker keeps asking for data that doesn't exist in the system , It will result in a large number of requests falling on the database in a short time , Cause too much database pressure , Even the database system .
This is called cache penetration .
How to solve ?
The query result is also cached if it is empty , The cache time is set a little shorter , Or should key Corresponding data insert Then clean up the cache .
Yes, it must not exist key To filter . You can put all the possibilities key Put it in a big Bitmap in , Query through the Bitmap Filter .( That is, the principle of the bloom filter : Blum filter )
6. What is a cache avalanche ?
Cache avalanche refers to the time from bulk to expiration of data in cache , And the amount of query data is huge , The request goes directly to the database , Cause too much pressure on the database and even downtime . Unlike cache breakdown , Cache breakdown refers to concurrent query of the same data , The cache avalanche is that different data has expired , A lot of data can't be found to look up the database .
How to solve ?
Common solutions are :
Even expiration
Add mutex lock
Cache never expires
Double layer cache strategy
Even expiration : Set different expiration times , Make the cache failure time as uniform as possible . It is usually possible to add a random value to the validity period or to plan the validity period uniformly .
Add mutex lock : It's consistent with the solution of cache breakdown , Let only one thread build the cache at the same time , Other threads block queuing .
Cache never expires : It's consistent with the solution of cache breakdown , Caches never expire physically , Update the cache with an asynchronous thread .
Double layer cache strategy : Use the primary and secondary layer cache :
Main cache : The validity period is set according to the experience value , Set the cache for primary reads , Load the latest value from the database after the primary cache fails .
Backup cache : It has a long validity period , Cache read when lock failed , When the primary cache is updated, the backup cache needs to be updated synchronously .
7. Redis How to optimize memory in use ?
Shorten the length of key value
Shortening the length of the value is the key , If the value is a large business object , You can serialize objects into binary arrays ;
First, we should streamline our business , Remove unnecessary attributes , Avoid storing useless data ;
The second is the selection of serialization tools , A more efficient sequencer should be chosen to reduce the byte array size ;
With JAVA For example , The built-in serialization method is not satisfactory in terms of speed or compression ratio , At this point, you can choose a more efficient serialization tool , Such as : protostuff,kryo etc.
Shared object pool
Object shared pool refers to Redis Internal maintenance [0-9999] Integer object pool for . Create a large number of integer types redisObject There is memory overhead , Every redisObject Internal structure accounts for at least 16 byte , It even exceeds the space consumption of the integer itself . therefore Redis Memory maintenance one [0-9999] Integer object pool for , Used to save memory . Except for integer value objects , Other types are list,hash,set,zset Internal elements can also use integer object pools . Therefore, in the development, on the premise of meeting the requirements , Try to use integer objects to save memory .
String optimization
because redis Lazy deletion mechanism , The space after string reduction is not released , Reserved as preallocated space . Try to add without updating .
Coding optimization
The so-called coding is what kind of underlying data structure is used to realize . Different codes will directly affect the memory occupation and read-write efficiency of data .
This needs to be mastered redis Underlying data structure . As a reference :

control key The number of
8. You redis Which deployment method to use ?
redis The deployment is divided into single nodes 、 Master-slave deployment (master-slave)、 Sentinel deployment (Sentinel)、 Cluster deployment (cluster).
A single node : That is, stand-alone deployment ;
Master-slave deployment : Divided into one master and one slave or one master and many slaves , The synchronization between master and slave is divided into full or incremental . Quantity synchronization :master Node passing BGSAVE Generate corresponding RDB file , And send it to slave node ,slave After receiving the write command, the node will master The sent file is loaded and written ; The incremental synchronization : That is to say master-slave Relationship building begins ,master Every time the data change command is executed, it will be synchronized to slave node . Generally, write requests are forwarded to master, Forward the read request to slave. Improved redis Performance of .
Sentinel deployment : There are sentinel clusters and Redis The master-slave cluster of , Sentry as a monitoring process in the operating system , Monitor each one accordingly Redis example , If master Service exception (ping pong The node does not reply and has exceeded a certain time ), It will be confirmed among multiple sentinels , If more than half of them confirm that the service is abnormal , On the other hand master The service goes offline , And elect the current one slave Node to convert to master node ; If slave Node service exception , It was also confirmed by several sentinels , Go offline . Improved redis Cluster high availability features , And the enhancement of horizontal expansion capability .

Cluster deployment : Belong to “ De centralization ” One way , Multiple master The node saves all the data in the entire cluster , And the data is based on key Conduct crc-16 Check the algorithm to hash , take key Hash into corresponding 16383 individual slot, and Redis cluster Each of the clusters master Nodes are responsible for different slot Range . Every master Multiple nodes can be configured under the node slave node , It can also be reused in the cluster sentinel Sentry improves the high availability of the entire cluster .

9. redis What should we pay attention to when implementing distributed locks ?
The locking process should ensure atomicity ;
Ensure that the lock added by who can only be unlocked by who , namely Redis The lock value, You need to pass in the same... When unlocking value To succeed , Guarantee value Uniqueness ;
Set lock timeout , Prevent other clients from being unable to acquire the lock when the lock adding party fails to release the lock abnormally , meanwhile , The timeout time should be greater than the business processing time ;
Use Redis command SET lock_key unique_value NX EX seconds To lock , Single command operation ,Redis Is a serial execution command , Therefore, only one can be locked successfully .
Low valley energy storage
Recommend open source SpringBoot+VUE System Twentythousand 、 Video tutorial attached :https://gitee.com/rodert/liawan-vue
Open personal wechat , Little buddy, you can add my big size , Quota co., LTD. , First come first served basis , If it's full again, it's really gone
Scan the QR code below to add my wechat ,2022, Huddle for warmth , Let's fight together .

边栏推荐
- Systematic arrangement | how many children's shoes have forgotten to be done carefully before the model development (practical operation)
- Requests cookie update value
- Web design and production final assignment report - minority music website
- Importbeandefinitionregistrar registers beans with the container
- "O & M youxiaodeng" active directory batch modification user
- 拦截器的具体概念
- Lua exports as an external link library and uses
- SQL operation: with expression and its application
- 【sdx62】QCMAP_ CLI manual dialing instructions
- Spark - Executor 初始化 && 报警都进行1次
猜你喜欢

slurm 使用教程

【科研笔记】Focal Loss

The best time to climb a ladder & sell shares (notes of the runner)

LeetCode——二叉搜索树的第k大节点(借助中序遍历)

How to use dataX to update the data in the downstream Oracle database with the update semantics

Write the first C application -- Hello, C

QML控件类型:SwipeView、PageIndicator

Learning signal integrity from scratch -- 7-si analysis and simulation

LeetCode 437. Path sum III - binary tree series question 13

Lua exports as an external link library and uses
随机推荐
【故障诊断】CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace b
爬梯子&&卖卖股份的最佳时期(跑路人笔记)
The beta version of move protocol is stable, and it is temporarily decided to expand the scale of the prize pool
Go 学习笔记
103. simple chat room 6: using socket communication
Ora - 15063: ASM discovered an insufficient number of Disks for diskgroup Recovery - - -
Is the Guoyuan futures account reliable? How can a novice safely open an account?
QML控件类型:SwipeView、PageIndicator
ORA-15063: ASM discovered an insufficient number of disks for diskgroup 恢复---惜分飞
Reasons and Countermeasures for ThinkPHP's session being unable to obtain session in different ways in the same controller
mysql笔记
The feeling of leaving full-time for a single month!
Lightweight CNN design skills
With these websites, do you still worry about job hopping without raising your salary?
获取DPI函数返回值永远是96 | 获取DPI函数返回值不正确 | GetDpiForMonitor/GetDeviceCaps返回值不正确的原因
mongo模糊查询,带有特殊字符需要转义,再去查询
Importbeandefinitionregistrar registers beans with the container
Tencent一面
【sdx62】QCMAP_ CLI manual dialing instructions
Debugging wechat built-in browser with chrome