As a back-end Developer , It's not just that developers need to master Redis, It also requires the operation and maintenance personnel to understand Redis. because Redis It is widely used , We also know the importance of it , At this point, I am often asked . Here 80 Avenue Redis In the interview question , The knowledge points include the foundation 、 Data structure instructions 、 High concurrency processing 、 Persistence 、 colony 、 Copy 、Redis Application etc. . If you are preparing for an interview or studying recently Redis, I believe this interview can meet your needs . I also hope I spent half a month sorting out these topics , The answers will help you .
Xiaobian shares this golden three silver four Java Back end development interview summary contains JavaOOP、Java Assembly containers 、Java abnormal 、 Concurrent programming 、Java Reflection 、Java serialize 、JVM、Redis、Spring MVC、MyBatis、MySQL database 、 Message middleware MQ、Dubbo、Linux、ZooKeeper、 Distributed & Data structure and algorithm 26 Three special technical points , They are all real interview questions summed up by Xiaobian in each big factory , There are already a lot of fans relying on this PDF Take down many big factories offer, Today, I would like to summarize and share with you ！【 Ongoing update ！】
Full version Java Address of interview questions ：2021 The latest collection of interview questions .
|1||middleware||Java It's an interview question （2021 The latest version ）|| https://my.oschina.net/u/4678580/blog/5012470|
|2||Microservices||Java Interview questions of microservice （2021 The latest version ）|| https://my.oschina.net/u/4678580/blog/5014045|
|3||Concurrent programming||Java Concurrent programming interview questions （2021 The latest version ）||https://my.oschina.net/u/4678580/blog/5017511|
|4||Java Basics||Java Basic knowledge interview questions （2021 The latest version ）||https://my.oschina.net/u/4678580/blog/5020008|
|5||Spring Boot||Spring Boot Interview questions （2021 The latest version ）||https://my.oschina.net/u/4678580/blog/5021192|
|6||Redis||Redis Interview questions （2021 The latest version ）||Ongoing update ！|
|7||Spring MVC||Spring MVC Interview questions （2021 The latest version ）||Ongoing update ！|
|8||Spring Cloud||Spring Cloud Interview questions （2021 The latest version ）||Ongoing update ！|
|9||MySQL Optimize||MySQL Optimize the interview questions （2021 The latest version ）||Ongoing update ！|
|10||JVM||JVM Performance tuning questions （2021 The latest version ）||Ongoing update ！|
|11||Linux||Linux Interview questions （2021 The latest version ）||Ongoing update ！|
|12||Mybatis||Mybatis Interview questions （2021 The latest version ）||Ongoing update ！|
|13||Network programming||TCP,UDP,Socket,Http Network programming interview questions （2021 The latest version ）||Ongoing update ！|
|14||Design patterns||Design pattern interview questions （2021 The latest version ）||Ongoing update ！|
|15||big data||Big data interview questions 100 Avenue （2021 The latest version ）||Ongoing update ！|
|16||Tomcat||Tomcat Interview questions （2021 The latest version ）||Ongoing update ！|
|17||Multithreading||Multithreaded interview questions （2021 The latest version ）||Ongoing update ！|
|18||Nginx||Nginx_BIO_NIO_AIO Interview questions （2021 The latest version ）||Ongoing update ！|
|19||memcache||memcache Interview questions （2021 The latest version ）||Ongoing update ！|
|20||java abnormal||java Abnormal interview questions （2021 The latest version ）||Ongoing update ！|
|21||Java virtual machine||Java Virtual machine interview questions （2021 The latest version ）||Ongoing update ！|
|22||Java aggregate||Java Assemble interview questions （2021 The latest version ）||Ongoing update ！|
|23||Git Common commands||Git Common commands （2021 The latest version ）||Ongoing update ！|
|24||Elasticsearch||Elasticsearch Interview questions （2021 The latest version ）||Ongoing update ！|
|25||Dubbo||Dubbo Interview questions （2021 The latest version ）||Ongoing update ！|
1、 What is? Redis?
Redis It's a use C Written in language , High performance of open source key-value Non relational cache database . It supports storage value There are more types , Include string( character string )、list( Linked list )、set( aggregate )、zset(sorted set -- Ordered set ) and hash（ Hash type ）.Redis All of the data is based on caching , So soon , Can handle over per second 10 Ten thousand read and write operations , Is the fastest known Key-Value DB.Redis You can also write data to disk , Ensure the security of data loss , and Redis The operation of is atomic .
2、Redis Data type of ？
Redis There are mainly 5 Type of data , Include String,List,Set,Zset,Hash, Meet most of the use requirements
3、 Use Redis What are the benefits ？
(1) Fast , Because the data is in memory , Be similar to HashMap,HashMap The advantage is the time to find and operate
The clutter is very low
(2) Support for rich data types , Support string,list,set,sorted set,hash
(3) Support transactions , The operations are all atomic , Atomicity means that changes to the data are either performed in full , Or none at all
(4) Rich features ： Available for caching , news , Press key Set expiration time , It will be deleted automatically after expiration
4、Redis comparison Memcached What are the advantages ？
- 1、Memcached All values are simple strings , redis As a substitute , Support for richer data classes
- 2、Redis Faster than Memcached Soon 3、Redis You can persist its data
5、Memcache And Redis What are the differences ？
1、 storage Memecache Store all the data in memory , It hangs when the power goes out , Data cannot exceed memory size . Redis Some of it is stored on the hard drive , This ensures data persistence
2、 Data support type Memcache Support for data types is relatively simple . Redis There are complex data types .
3、 Using the underlying model is different The underlying implementation between them And the application protocol of communication with the client is different . Redis Build it yourself VM Mechanism , Because the normal system calls system functions , It's a waste of time moving and requesting .
6、Redis Single process, single thread ？
- answer ： Redis Single process, single thread , redis Use queue technology to change concurrent access into serial access , Eliminate the cost of traditional database serial control .
7、 What is the maximum storage capacity of a string type value ？
- answer ： 512M
8、Redis What is the persistence mechanism of ？ Advantages and disadvantages of each ？
Redis There are two persistence mechanisms RDB（ Default ） and AOF Mechanism :
RDB： yes Redis DataBase Abbreviated snapshot
- RDB yes Redis Default persistence method . Save the memory data to the hard disk in the form of snapshot according to a certain time , The corresponding generated data file is dump.rdb. Through... In the configuration file save Parameter to define the period of the snapshot .
- Only one file dump.rdb, Easy persistence .
- Good disaster tolerance , A file can be saved to a safe disk .
- Maximize performance ,fork Sub process to complete the write operation , Let the main process continue processing commands , So it is IO Maximize . Use sheet Only child processes are used for persistence , The main process will not do anything IO operation , To ensure the redis A high performance
- When the data set is large , Than AOF It's more efficient to start .
- Data security is low .RDB It's persistence at intervals , If between persistence redis failure , How many will happen It is lost . So this way is more suitable when the data requirements are not rigorous )
- AOF（Append-only fifile) Persistence mode ： Means all command line records to redis Command please Ask for the format of the agreement Fully persistent storage ) Save as aof file .
AOF： Persistence ：
- AOF Persistence ( namely Append Only File Persistence ), Will be Redis Each write command executed is recorded in a separate log file
- in , When restarting Redis It will recover the data from the persistent log again . When both modes are on at the same time , Data recovery Redis Preference will be given AOF recovery
- Data security ,aof Persistence can be configured appendfsync attribute , Yes always, Every time Command operations are recorded To aof Once in the file .
- adopt append Mode write file , Even if the server goes down , Can pass redis-check-aof Tools to solve data one A sexual question .
- AOF The mechanism rewrite Pattern .AOF The document was not rewrite Before （ When the file is too large, the command Do merge rewrite ）, You can delete some of these commands （ For example, misoperation flflushall）)
- AOF File than RDB The file is big , And the recovery speed is slow .
- When the data set is large , Than rdb Low starting efficiency .
What are the advantages and disadvantages of two kinds of persistence ？
- AOF File than RDB High update frequency , priority of use AOF Restore data .
- AOF Than RDB Safer and bigger
- RDB Performance ratio AOF good
- If both have priority loading AOF
9、Redis Common performance problems and solutions ：
10、Redis Delete strategy of expired key ？
11、Redis Recycling strategy for （ Elimination strategy ）?
12、 Why? Redis You need to put all the data in memory ？
- answer ：Redis In order to achieve the fastest read-write speed, read all data into memory , And write data to disk asynchronously . therefore redis It has the characteristics of fast and data persistence . If the data is in memory , disk I/O Speed is a serious effect redis Performance of . Today, memory is getting cheaper , redis Will be more and more popular . If the maximum memory usage is set , After the number of existing records reaches the memory limit, the new value cannot be inserted .
13、Redis Do you understand the synchronization mechanism of ？
- answer ：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 buffffer, 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 .
14、Pipeline What are the benefits , Why use pipeline？
- answer ： 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 .
15、 Have you ever used Redis colony , 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 .
16、Redis When will the cluster scheme cause the whole cluster to be unavailable ？
- answer ： Yes A, B, C Three node cluster , Without copying the model , If node B failed , Then the whole cluster will think that it lacks 5501-11000 This range of slots is not available .
17、Redis Supported by Java What does the client have ？ Which is the official recommendation ？
- answer ： Redisson、Jedis、lettuce wait , Official recommendation Redisson.
18、Jedis And Redisson What are the advantages and disadvantages of comparison ？
- answer ： Jedis yes Redis Of Java Implemented client , Its API Provides a more comprehensive Redis Command support ;Redisson Distributed and extensible Java data structure , and Jedis comparison , The function is relatively simple , String operation is not supported , Sort is not supported 、 Business 、 The Conduit 、 Partition etc. Redis characteristic .Redisson The aim is to promote the user's understanding of Redis Separation of concerns , This allows users to focus more on processing business logic .
19、Redis How to set password and verify password ？
- Set the password ： confifig set requirepass 123456 Authorization code ： auth 123456
20、 say something Redis The concept of hash slot ？
- answer ： Redis Cluster does not use consistency hash, It introduces the concept of hash slot , Redis Cluster has 16384 Hash slot , Every key adopt CRC16 Check pair 16384 Take the mold to decide which slot to place , Each node in the cluster is responsible for part of hash Slot .
21、Redis What is the master-slave replication model of a cluster ？
- answer ： In order to make the cluster available even if some nodes fail or most nodes cannot communicate , So the cluster uses the master-slave replication model , Each node will have N-1 A replica .
22、Redis Are there any write operations lost in the cluster ？ Why? ？
- answer ：Redis There is no guarantee of strong data consistency , This means that in practice, the cluster may lose write operations under certain conditions .
23、Redis How are clusters replicated ？
- answer ： Asynchronous replication
24、Redis What is the maximum number of nodes in the cluster ？
- answer ： 16384 individual .
25、Redis How do clusters choose databases ？
- answer ： Redis At present, the cluster is unable to make database selection , Default in 0 database .
26、 How to test Redis The connectivity of ？
- answer ： Use ping command .
27、 How to understand Redis Business ？
1） A transaction is a separate isolation operation ： All commands in the transaction are serialized 、 To execute in order . Transaction is in the process of execution , Will not be interrupted by command requests from other clients .
2） A transaction is an atomic operation ： The commands in the transaction are either all executed , Or none of it .
28、Redis What are the transaction related commands ？
- answer ： MULTI、EXEC、DISCARD、WATCH
29、Redis key How to set the expiration time and permanent validity of ？
- answer ： EXPIRE and PERSIST command .
30、Redis How to optimize memory ？
- answer ： Use hash table as much as possible （ hashes）, Hash table （ It means that there is little storage in the hash table ） The memory used is very small , So you should try to abstract your data model into a hash table . Such as your web There is a user object in the system , Don't name for this user , surname , mailbox , Password settings are separate key, Instead, all the information of this user should be stored in a hash table .
31、Redis How the recycling process works ？
answer ： A client runs a new command , Added new data .Redi Check memory usage , If it is greater than maxmemory The limitation of , Then recycle according to the set strategy . A new order is executed , wait . So we're constantly going through the boundaries of memory limitations , By constantly reaching the border and then constantly recycling back below the border . If a command results in a large amount of memory being used （ For example, the intersection of a large set is saved to a new key ）, It will not be long before the memory limit is exceeded by the memory usage .
32、 There are ways to reduce Redis The memory usage of ？
- answer ： If you're using 32 Bit Redis example , You can make good use of Hash,list,sorted set,set And so on , Because usually a lot of small Key-Value It can be stored together in a more compact way .
33、Redis What happens when you run out of memory ？
- answer ： If the set upper limit is reached ,Redis The write command of will return an error message （ But the read command can return normally .） Or you can put Redis When caching is used to configure the obsolescence mechanism , When Redis Reaching the memory limit will flush out old content .
34、 One Redis How many instances can be stored at most keys？List、Set、Sorted Set How many elements can they store at most ？
- answer ： Theoretically Redis Can handle up to 232 Of keys, And tested in practice , Each instance has at least 2 Billion 5 Ten million keys. We are testing some of the larger values . whatever list、set、 and sorted set You can put 232 Elements . let me put it another way , Redis The storage limit of is the available memory value in the system .
35、MySQL Are there in 2000w data ,redis The only known 20w The data of , How to ensure redis The data in is hot data ？
- answer ： Redis When the size of the memory data set rises to a certain size , Data elimination strategies will be implemented . Related knowledge ： Redis Provide 6 A data culling strategy ：
- volatile-lru： From the set of data for which the expiration time has been set （ server.dbi.expires） Select the least recently used data in
- volatile-ttl： From the set of data for which the expiration time has been set （ server.dbi.expires） To select the data to be expired
- volatile-random： From the set of data for which the expiration time has been set （ server.dbi.expires） In the arbitrary selection of data elimination
- allkeys-lru： From the data set （ server.dbi.dict） Select the least recently used data in
- allkeys-random： From the data set （ server.dbi.dict） In the arbitrary selection of data elimination
- no-enviction（ deportation ） ： Exclusion data
36、Redis The most appropriate scene ？
1、 Session cache （ Session Cache）
One of the most common USES Redis Is the session cache （ session cache）. use Redis Cache sessions than other stores （ Such as Memcached） The advantage is that ：Redis Provide persistence . When maintaining a cache that is not strictly consistent , If all of the user's cart information is lost , Most people won't be happy , Now? , Will they do that again ？ Fortunately, , With Redis Years of improvement , It's easy to figure out how to use it properly Redis To cache the documents for the session . Even well-known business platforms Magento Also provide Redis Plug in for .
2、 Full page caching （ FPC）
Except for basic conversations token outside , Redis It's also very simple FPC platform . Back to consistency , Even if it restarts Redis example , Because there is disk persistence , Users won't see the page load speed drop , This is a huge improvement , similar PHP Local FPC. Once again to Magento For example ,Magento Provides a plug-in to use Redis As the full page cache backend . Besides , Yes WordPress For users of , Pantheon There is a very good plug-in wp-redis, This plugin will help you load the pages you have visited as quickly as possible .
Reids A big advantage in the field of memory storage engines is that it provides list and set operation , This makes Redis Can be used as a good message queue platform .Redis Operations used as queues , It's like a native programming language （ Such as Python） Yes list Of push/pop operation . If you quickly in Google Mid search “ Redis queues”, You'll find plenty of open source projects right away , The purpose of these projects is to leverage Redis Create great back-end tools , To meet various queue requirements . for example , Celery There is a background that is used Redis As broker, You can check it out here .
4, Ranking List / Counter
Redis Incrementing or decrementing Numbers in memory works very well . aggregate （ Set） And ordered set （ Sorted Set） It also makes it very easy for us to perform these operations ,Redis It just happens to provide both data structures . therefore , We want to get the highest ranked from the sorted set 10 Users – We call it “ user_scores”, We just need to execute like this ： Of course , This assumes that you are doing an incremental sort based on your users' scores . If you want to return the user and the user's score , You need to do it this way ： ZRANGEuser_scores 0 10 WITHSCORES Agora Games This is a good example , use Ruby Realized , Its leaderboard is to use Redis To store data , You can see it here .
5、 Release / subscribe
Last （ But certainly not the least ） yes Redis Release / Subscribe to the function . Release / There are a lot of usage scenarios for subscriptions . I've seen people using it in social networking connections , It can also be used as a release-based publication / Subscribe to script triggers , Even with Redis Release / Subscribe to set up a chat system ！
37、 If Redis There are 1 One hundred million key, Among them is 10w individual key It starts with a fixed known prefix , If you find them all ？
38、 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 ？
- answer ： 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 . Generally, we need to add a random value to the time , Spread the expiration time a little bit .
39、 Have used Redis Do asynchronous queues , How do you use ？
40、 Have used Redis Distributed locks , What is it ？
41、 How to realize... In the cluster session Shared memory ？
42、memcached And redis The difference between ？
43、 see Redis What commands are used for usage and status information ？
44、Redis What happens when you run out of memory ？
- If the set upper limit is reached ,Redis The write command of will return an error message （ But the read command can return normally .） or You can put Redis When caching is used to configure the obsolescence mechanism , When Redis Reaching the memory limit will flush out old content .
45、Redis It's single threaded , How to improve multicore CPU Utilization ratio ？
- You can deploy multiple on the same server Redis Example , And use them as different servers , At some point , In any case, a server is not enough , therefore , If you want to use more than one CPU, You can think about slicing （shard）
46、 One Redis How many instances can be stored at most keys？List、Set、Sorted Set How many elements can they store at most ？
47、Redis Common performance problems and solutions ？
(1) Master It's best not to do any persistence work , Such as RDB Memory snapshot and AOF Log files
(2) If the data is important , Some Slave Turn on AOF The backup data , The policy is set to synchronize once per second
(3) For master-slave replication speed and connection stability ,Master and Slave Preferably on the same LAN
(4) Try to avoid adding slaves to stressed master libraries
(5) Master and slave replication do not use graphical structures , One - way linked list structure is more stable , namely ：Master <- Slave1 <- Slave2 <- Slave3...
This structure is convenient to solve the problem of single point failure , Realization Slave Yes Master Replacement . If Master Hang up , It can be enabled immediately Slave1 do Master, The other is constant .
48、Redis What kinds of persistence are provided ？
49、 How to choose the right way to persist ？
50、 Modify the configuration without restarting Redis Will it take effect in real time ？
This is the end of the article shared by Xiaobian , Sorting is not easy to , Welcome to exchange , If you like the articles shared by Xiaobian, please pay attention to me , Thank you for your support ！