当前位置:网站首页>Basic knowledge of redis
Basic knowledge of redis
2022-06-30 04:12:00 【Winter dream chaser】
Redis So widely used in Internet technology storage , Almost all back-end technology interviewers are Redis The use and principle of 360° It's difficult . Take it one at a time as an Internet company offer Face bully of ( Allow me to use the rhetoric of exaggeration ), Beat countless competitors , Each time can only see countless lonely figure disappointed to leave , A little guilty , On a lonely night , I thought over the pain , Decided to start writing 《 Condole interviewer 》 series , I hope it can help you in your future interview , To the interviewer 360° The counterattack , Ask your interviewer , Let the colleagues in the interview come back , Crazy harvest factory offer!

The interview begins
A paunch , A middle-aged man in a plaid shirt , Take one full of scratches mac Coming to you , Look at the Balding Hair , I thought it must be NIMA's top architect ! But we are full of poetry and calligraphy , Empty is not empty .

Hello, young man , Look at your resume. It's used in your project Redis, Why do you use Redis?
I can't help but scold , What's the problem , We all use this one , But you can't say .
I mean it : Hello, handsome and charming interviewer , Because traditional relational databases like Mysql It can't be applied to all the scenes , For example, the stock deduction of seckill ,APP Home page traffic peak and so on , It's easy to crack the database , So cache middleware is introduced , At present, the commonly used cache Middleware in the market is Redis and Memcached But he took their advantages and disadvantages into account , Finally, I chose Redis.
As for the more detailed comparison, friends remember to check Redis and Memcached The difference between , For example, the advantages and disadvantages of the two and their respective scenes , I will write it out later when I have time .
The young man , I'll ask you again ,Redis What are the data structures ?
String、Hash、List、Set、SortedSet.
Here I believe 99% All of our readers can answer Redis Of 5 Basic data types . If we can't answer the question, we need to make up for it , You know that the five most suitable scenes are better .
however , If you are Redis Middle and advanced users , And you need to highlight the difference between you and other candidates in this interview , You need to add the following data structures HyperLogLog、Geo、Pub/Sub.
If you want more points , Then you said you played Redis Module, image BloomFilter,RedisSearch,Redis-ML, At this time the interviewer's eyes start to shine , I thought this young man There's something .
notes : I answered in an interview Redis When it comes to relevant questions , Often mentioned BloomFilter( The bloon filter ) There are a lot of real scenarios for this thing , And it's really fragrant , The principle is easy to understand , Take a look at the article and you can talk in front of the interviewer .
If there's a lot of key You need to set the expiration date at the same time , What should we pay attention to in general ?
If a large number of key Expiration time is set too centrally , By the time it expires ,Redis There may be a short-term stumbling . In serious cases Cache avalanche , We usually need to add a random value to the time , Spread the expiration time a little bit .
E-commerce home page often uses timed tasks to refresh the cache , It's possible that a large number of data failure times are very concentrated , If the failure time is the same , And just at the point of failure, a large number of users swarmed in , It is possible to cause Cache avalanche
Then you used Redis Distributed locks , What is it ?
First take setnx To fight for the lock , After grabbing it , Reuse expire Add an expiration time to the lock to prevent it from forgetting to release .
At this time, the other party will tell you that you have a good answer , Then ask if you are setnx After performing expire The previous process was unexpected crash Or restart maintenance , What then ?
You have to give surprising feedback : alas , Yeah , The lock will never be released . And then you need Grab your head , Pretend to think for a moment , It seems that the next result is the result of your active thinking , Then answer : I remember set Instructions have very complex parameters , This should be able to put setnx and expire To synthesize an instruction for use !
The other person will smile , I began to meditate : Um. , This boy is not bad , It's beginning to be interesting . If Redis There are 1 One hundred million key, Among them is 10w individual key It starts with a fixed known prefix , How to find them all ?
Use keys The command can scan out the key list .
The other side then asked : If this redis Providing services for online business , That use keys What's wrong with the instructions ?
At this time, you have to answer Redis A key feature :Redis Of single thread .keys Instructions can cause threads to block for a period of time , Online services will pause , Until the command is executed , Service can be restored . It can be used at this time scan Instructions ,scan Instructions It can extract the specified patterns without blocking key list , But there is a certain probability of repetition , In the client to do a duplicate can , But the overall time spent will be more than the direct use of keys Commander .
however , Incremental iteration commands are not without drawbacks : for instance , Use SMEMBERS The command returns all the elements currently contained in the set key , But for SCAN For this kind of incremental iteration command , Because in the process of incrementally iterating on the bond , The key may be modified , So the incremental iteration command can only provide limited guarantee for the returned elements .
Have used Redis Do asynchronous queues , How do you use ?
In general use list Structure as a queue ,rpush Production news ,lpop News consumption . When lpop When there is no news , Be appropriate sleep Try again later .
If the other side asks, can we not use sleep Well ?
list There's also a directive called blpop, When there is no news , It will block until the news comes .
If the other side continues to ask if it can produce one consumption many times ?
Use pub/sub Theme subscriber mode , Can achieve 1:N Message queue of .
If the other side continues to ask pub/sub What's the downside ?
When consumers are offline , Production messages will be lost , You have to use a professional message queue like RocketMQ etc. .
If the other side is inquisitive TM Questioning Redis How to implement delay queue ?
This is a series of moves , I guess now you'd like to beat the interviewer to death ( The interviewer wanted to kill himself. Why did he ask so many questions he didn't know ), If you have a baseball bat in your hand , But you are very restrained . Calm down the excited heart , And then he replied with an air of self-respect : Use sortedset, Take the time stamp as score, The content of the message is key call zadd To produce news , Consumers use zrangebyscore Instructions for N Second before the data polling for processing .
Come here , The interviewer has secretly thumbed you up . And I have given it to you in silence A+, But what he doesn't know is that at the moment you've raised your middle finger , Behind the chair .
Redis How to persist ? How does the master and slave data interact ?
RDB Mirror full persistence ,AOF Do incremental persistence . because RDB It will take a long time , Not real time enough , During shutdown, a lot of data will be lost , So we need to AOF To work with . stay redis When the instance is restarted , Will use RDB Persistent files rebuild memory , Reuse AOF Replay the recent operation instructions to fully recover the state before restart .
It's easy to understand , hold RDB It can be understood as the data of the whole table ,AOF It is better to understand the log of each operation , When the server restarts, first get all the data in the table , But he may not be complete , You play back the log again , The data is not complete . however Redis Its own mechanism is AOF Persistence is on and exists AOF When you file , Priority load AOF file ;AOF Close or AOF When the file does not exist , load RDB file ; load AOF/RDB Behind the document city ,Redis Successful launch ;AOF/RDB When there is an error in the file ,Redis Failed to start and print error message
The other side asked what would happen if the machine suddenly lost power ?
Depending on AOF journal sync Configuration of properties , If performance is not required , Every time I write an instruction sync Here's the disk , There's no loss of data . But with high performance, every time sync It's unrealistic , Usually use timing sync, such as 1s1 Time , The most you can lose at this time 1s The data of .
The other side asked RDB What is the principle of ?
Just give me two words ,fork and cow.fork Refer to redis By creating subprocesses RDB operation ,cow refer to copy on write, After the subprocess is created , Parent child processes share data segments , The parent process continues to provide read and write Services , Writing dirty page data will gradually separate from subprocesses .
notes : To answer this question , If you can still say AOF and RDB Advantages and disadvantages , I think I'm the interviewer. I'll give you some compliments on this issue , In fact, there is a big difference between the two , And it's about Redis Data synchronization of cluster and so on . You can also leave a message if you want to know , I will write a special article to introduce .
Pipeline What are the benefits , Why use pipeline?
It can be many times IO Round trip time is reduced to one time , Premise is pipeline There is no causal correlation between the instructions executed . Use redis-benchmark We can find the influence when we do the pressure test redis Of QPS An important factor in the peak value is pipeline Number of batch instructions .
Redis Do you understand the synchronization mechanism of ?
Redis You can use master-slave synchronization , From slave synchronization . The first synchronization , The master node does it once bgsave, At the same time, the subsequent modification operations are recorded in memory buffer, To be completed RDB Full file synchronization to replication node , When the replication node acceptance is complete, it will RDB The image is loaded into memory . After loading , Then inform the main node to synchronize the modified operation records to the replication node for replay, and the synchronization process is completed . The subsequent incremental data passes through AOF Log synchronization , It's a bit like a database binlog.
Have you ever used Redis colony , How to guarantee the high availability of cluster , What is the principle of clustering ?
Redis Sentinal Focus on high availability , stay master It will automatically slave Upgrade to master, Continued provision of services .
Redis Cluster Focus on scalability , In a single redis When there is not enough memory , Use Cluster For fragmentation storage .
The end of the interview
Young man, you can , When can I come to work , Or come tomorrow ?
You try to be calm , I still need to rent a house in such a hurry , Maybe next Monday .
well Think this kid is so NB Is it a lot of Offer On the hand , No, I have to call hr Give him more money .
To last , You can't help but praise yourself !
summary
In a technical interview , Whether it's Redis Or something , If you can give a real example , Or directly say that the problems and gains of the development process will add a lot to the impression of the interviewer , The answer should be more logical , Don't be a little East and a little west , It's easy to get dizzy .
Another point is that I ask you why Redis You don't have to answer the questions as soon as you come up , You can answer this way :
Hello, handsome interviewer , First of all, our project DB There's a bottleneck , Especially the scene of seckill and hot data DB Basically, I can't carry it , Then we need to add caching middleware , At present, there are some cache middleware on the market Redis and Memcached , Their advantages and disadvantages ……, Combine these and then combine the characteristics of our project , In the end, who we chose when we chose the technology .
If you are so methodical , I have answered my questions reasonably and said so many knowledge points beyond my questions , I think you're not just someone who can write code , Your logic is clear , You choose technology , I have my own understanding and thinking about middleware and projects , To put it bluntly, it's your offer There's a play. .

All right, everyone , The above is the whole content of this article , I'll update a few later every week 《 Condole interviewer 》 Series and Java Technology stack related articles . If you have anything to know , Or leave me a message , I'll write it as soon as I have time , We make progress together .
边栏推荐
- GIS related data
- Introduction to cloud native + container concept
- 数据链路层详解
- NER中BiLSTM-CRF解读score_sentence
- After the win10 system uses the browser to download, the content is moved or deleted without reason
- errno和perror
- Interpretation score of bilstm-crf in NER_ sentence
- When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?
- RPC correction based on arcpy API
- Modifier of JS regular expression
猜你喜欢

When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?
![[Thesis reading | deep reading] dane:deep attributed network embedding](/img/c7/60f36c2748b8cd7544b7ef14dc309e.png)
[Thesis reading | deep reading] dane:deep attributed network embedding

Jour 9 Gestion des scripts et des ressources

About manipulator on Intelligent Vision Group
![[cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)](/img/08/b390810d457af5e4470d9743b01ca1.png)
[cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)

第十二天 进阶编程技术

【模糊神经网络预测】基于模糊神经网络实现水质预测含Matlab源码

EasyCVR部署服务器集群时,出现一台在线一台不在线是什么原因?

第九天 脚本与资源管理

Slam mapping, automatic navigation and obstacle avoidance based on ROS (bingda robot)
随机推荐
[cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)
If you encounter problems when using spark for the first time, please ask for help
[operation] getting started with MySQL on May 23, 2022
Do280 private warehouse persistent storage and chapter experiment
Green new power and "zero" burden of computing power -- JASMINER X4 series is popular
487-3279(POJ1002)
base64.c
管道实现进程间通信之命名管道
网络层详解
Concatenation of Languages(UVA10887)
.NET 7 的 JWT 配置太方便了!
[note] on May 27, 2022, MySQL is operated through pychart
Indefinite parameters of JS function
Interface testing -- how to analyze an interface?
第九天 脚本與資源管理
Unity when entering a string in the editor, escape the input of characters
Share an example of a simple MapReduce method using a virtual machine
Project safety and quality
毕业设计EMS办公管理系统(B/S结构)+J2EE+SQLserver8.0
Use ideal to connect to the database. The results show some warnings. How to deal with this part