当前位置:网站首页>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 .

边栏推荐
- PCM data format
- Is the Guoyuan futures account reliable? How can a novice safely open an account?
- What is the value of the FC2 new domain name? How to resolve to a website?
- 网页设计与制作期末大作业报告——动画家宫崎骏
- Wisdom, agriculture, rural areas and farmers digital Wang Ning: Tips for beginners on the first five days of trading
- ORA-15063: ASM discovered an insufficient number of disks for diskgroup 恢複---惜分飛
- Spark - executor initialization &
- requests cookie更新值
- Pourquoi golang ne recommande - t - il pas ceci / self / me / this / _ Ça.
- 【故障诊断】使用多线程,程序不报错,但就是不运行
猜你喜欢

Redis 主从复制

window10无法访问局域网共享文件夹

Postman uses (reads) JSON files for batch testing

About SSM integration, this is enough ~ (nanny level hands-on tutorial)

Circuit board layout and wiring precautions for analog / digital mixed signals

JUC - 线程中断与线程等待、唤醒(LockSupport)

Web design and production final assignment report - minority music website
![Chapter VIII programmable interface chip and application [microcomputer principle]](/img/63/5f01a74defd60f0d4a8f085ff0e2e9.png)
Chapter VIII programmable interface chip and application [microcomputer principle]

NFT mall building digital collection mall building digital collection market digital collection development company

Zhongmin online: sharing online channel resources with "points" as the link
随机推荐
Online document collaboration: a necessary efficient artifact for office
exness:欧洲央行行长拉加德重申计划在7月会议上加息
[learn FPGA programming from scratch -39]: Advanced - syntax - unit test of hardware module: simulation excitation, testbench
What is a forum virtual host? How to choose?
Disturbed when programmers are programming? Daily anecdotes
Solve the problem that swagger2 displays UI interface but has no content
How to deal with too small picture downloaded from xuexin.com
Write the first C application -- Hello, C
【故障诊断】CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace b
Digital economy Wang Ning teaches you how to correctly choose short-term investment
tinymce. Init() browser compatibility issue
JUC - 线程中断与线程等待、唤醒(LockSupport)
[从零开始学习FPGA编程-39]:进阶篇 - 语法-硬件模块的单元测试:仿真激励、testbench
High precision positioner formwork
网页设计与制作期末大作业报告——小众音乐网站
NFT mall building digital collection mall building digital collection market digital collection development company
Chapter VIII programmable interface chip and application [microcomputer principle]
Systematic arrangement | how many children's shoes have forgotten to be done carefully before the model development (practical operation)
Use putty to configure port mapping to realize the access of the external network to the server
Kotlin project reports an error and lacks coroutinecontext dependency