"Interview Heart Sutra"---Redis foundation

One leaf is blind, but I don’t see Offer

Preface

Redis has a pivotal position in today's world of back-end technology. Almost all back-end technical interviewers will cross-examine the interviewees in an all-round way around the principles and use of Redis. Interrogation from Redis may be late, but it will never be absent. Old Na couldn't bear to see the self-confident eyes dimmed by the interviewer. On a dark and windy night for a month, I finally made up my mind to collect and sort out Redis interview materials, and write the "Interview Heart Sutra" series, hoping to universalize all living beings.

Interview begins

A sloppy bald middle-aged man walks towards you holding a scratched Mac. Looking at your sparse hair, thinking I fuck, this is at least a senior architect. But those of us who have watched "Interview Heart Sutra" can still be calm and stable

Insert picture description here

Hello boy, it is written on your resume that Redis is used in the project, why use Redis?

At this time, you couldn't help cursing inwardly, your head was bald, and the questions asked were so ordinary, just this? But you cannot show it.

Seriously replied: Hello, handsome and charming interviewer . At that time, because more and more people used the project, only using traditional relational databases (such as MySQL) could no longer meet the needs of the project. Considering the performance and concurrency of the project, it is necessary to introduce cache middleware into the project. After comprehensively comparing the advantages and disadvantages of the commonly used cache middleware Redis and Memcache at that time, I finally decided to choose Redis.

Here is likely to ask you what are the differences between Redis and Memcache, and their respective advantages and disadvantages. Interested young heroes can go to check the information to understand, I will also publish an article to introduce the comparison in detail

What data types do you have in Redis?

The answer in one go: redis supports multiple types of data structures, there are 5 commonly used, namely strings, hashes, lists, sets, sorted sets

These five data structures must be done backwards and forwards in one go. It is better to know the usage scenarios and underlying implementation principles of each data structure

However, if you want to stand out, you also need to add the following data structures: bitmaps, hyperloglogs, geospatial indexes, streams

The answer here is basically the level that makes the interviewer's eyes open

Boy, do you know the underlying implementation of Redis String?

At this moment, you think: I'm just here to interview a CV siege lion with a monthly salary of 1K, why should I go through this? Bah, shameless! But you still can’t show it, you can’t let the interviewer’s tricks succeed

Reflections do little, A: string object underlying data structure implemented as a simple dynamic string (SDS) and stored directly . (Note: SDS is a structure defined by redis)

As long as the SDS can be mentioned here, it is basically enough. If you can also introduce the internal structure of the SDS structure in detail, it would be better

Do you understand Redis persistence? Please briefly introduce

Feng Qingyun said: There are two types of Redis persistence, RDB and AOF

RDB does full persistence (Redis default persistence method). According to a certain time period strategy, the memory data is saved to the binary file of the hard disk in the form of snapshot. The corresponding data file is dump.rdb, and the period of the snapshot is defined by the save parameter in the configuration file. (A snapshot can be a copy of the data it represents, or a copy of the data.)

AOF for incremental persistence: Redis will append each received write command to the end of the file through the Write function, similar to MySQL binlog. If necessary, you can re-execute the write command saved in the file to rebuild the entire redis database in memory.

The mechanism of Redis itself is: when AOF persistence is enabled and an AOF file exists, the AOF file is loaded first. When AOF persistence is closed or there is no AOF file, load the RDB file. After the AOF/RDB file is successfully loaded, Redis starts successfully. If there is an error in the AOF/RDB file, Redis fails to start and prints an error message

Do you know Pipeline? Please briefly introduce

Multiple commands can be packaged and sent to redis for processing. After the processing is completed, the processing results are packaged in order and returned together. The advantage is that it can reduce I/O times and improve redis throughput. However, there are two points to note: the commands in a pipeline cannot have a causal relationship with each other. In addition, there should not be too many commands in a pipeline, otherwise the amount of data will be too large, which will increase the waiting time of the client and may also cause network congestion. You can split a large number of commands into multiple small pipeline commands to complete.

Have you used Redis distributed lock? How to achieve

Use setnx to compete for the lock first, and use expire to add an expiration time to the lock after grabbing it to prevent forgetting to release the lock

What happens if the process crashes unexpectedly or restarts maintenance after executing setnx and before executing expire?

Pretending to be surprised: If this is the case, the lock will never be released! At this point, you can make a thinking state (the thinking time should not be too long, it may make the interviewer mistakenly think that you don't know how to deal with it, it is recommended that you do not know how to deal with it), and say: set command can be followed by parameters to realize locking and setting expiration time Two operations ensure atomicity of operations. (Command: SET key value EX second NX )

The interviewer smiled, um, it’s okay

Have you used redis as an asynchronous queue? Explain the implementation

Generally, the list structure is used as a queue, lpush produces messages, and rpop consumes messages. When rpop has no messages, sleep for a while and try again.

The interviewer asks again, can we not use sleep?

Yes, use blocking instructions in the list structure, such as brpop . When there are no elements in the list, the list will be blocked until the waiting timeout or pop-up elements are found.

Ask again, what if I want to produce once and consume many times?

You can use the pub/sub publish-subscribe model to implement a 1:N message queue

Ask again, what are the disadvantages of the pub/sub model?

In the event that the consumer goes offline, the produced message will be lost. You can use professional message queues to ensure that messages are not lost, such as rocketMQ, rabbitMQ, etc.

Ask again, how does Redis implement delay queues?

At this time you may have the urge to ask the second battalion commander to pull the Italian cannon up. But for the interview to go smoothly, you still have to suppress your inner impulse and keep smiling

Slowly replied: Use sortedset , use timestamp as score , message content as key , producer calls zadd to produce messages, consumer uses zrangebyscore command to get messages N seconds ago, polling for processing

Do you know about Redis transactions? What happens if a certain/certain command in the transaction fails?

If a command in the transaction fails, other commands in the transaction will continue to be executed. In addition, Redis transactions do not support roolback

If there are 100 million keys in Redis, 10w of them start with a fixed, known prefix, how to find them all?

Use the keys command to scan out the key list of the specified mode.

If this redis is providing services to online businesses, what are the problems with using the keys command?

At this time, you have to answer a key feature of redis: redis is single-threaded . The roolback keys instruction will cause the thread to block for a period of time, and the online service will pause. The service cannot be restored until the instruction is executed. At this time, you can use the scan command. The scan command can extract the key list of the specified mode without blocking, but the key may be repeated to a certain extent, and it is enough to do a deduplication on the client. The overall scan time will be longer than using the keys command.

There are 2000w data in MySQL, and only 20w data can be stored in redis. How to ensure that the data in redis is hot data?

When the client adds new data to Redis. Redis will check the memory usage, and if it is greater than the maxmemory limit, it will recycle the old data according to the set elimination strategy .

Have you used Redis cluster? How to ensure the high availability of the cluster? What is the principle of the cluster?

Redis Sentinal focuses on high availability. When the master is down, it will automatically promote the slave to the master and continue to provide services.

Redis Cluster focuses on scalability. When a single redis memory is insufficient, Cluster is used for shard storage.

Talk about data sharding of Redis cluster

Redis cluster does not use consistent hash, but introduces the concept of hash slot. The Redis cluster has 16384 hash slots. After CRC16 checks, each key modulates 16384 to determine which slot to place. Each node in the cluster is responsible for a part of the hash slot.

End of interview

The boy is pretty good, when do you have time to come to work? Or just tomorrow.

You pretend to be calm: in such a hurry, I still want to rent a house. Or next Monday

The interviewer thought to himself, so NB, can’t let him run away, and immediately ask HR to add money to him

Write at the end

I don’t know if you have such a feeling that many things seem very simple and you think you can do it too, but you just don’t want to do it; a lot of knowledge seems to be known to yourself, but when the interviewer asks, you can’t The logical answer was clear and complete, and afterwards I felt: I can do it all by myself, but I didn’t perform well...

I did the same before. But now I understand that I am not lazy, I just don't want to admit that I am a trash. Do more, think more, sum up more! friend

Stay hungry, stay foolish
strives to improve the visibility and breadth of your own skills. It is a necessary condition to pass the interview.
Usually, think more and summarize more, so that you can talk during the interview.
Besides, staying confident and calm will make you look more reliable. Improve interview pass rate

This article is based on the usual interview experience, summarized and perfected. Due to space reasons, some of the answers may not be perfect. I will analyze the common test sites during interviews in more detail in a later article.

Finally, I wish you all go ashore soon. Our slogan is: We must win! ! !

Your point of praise and attention is very useful to me

Guess you like

Origin blog.csdn.net/weixin_39815001/article/details/108709773