In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the Redis high-frequency interview questions". In the daily operation, I believe that many people have doubts about the Redis high-frequency interview questions. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for everyone to answer the questions of "what are the Redis high-frequency interview questions?" Next, please follow the editor to study!
Through interviewing a number of large Internet companies, the following high-frequency interview questions are summarized:
1. Delete policy for redis expired keys?
Timed deletion: create a timer timer while setting the expiration time of the key. Let the timer delete the key immediately when the expiration time of the key is approaching.
Lazy deletion: let the key expire, but every time you get the key from the key space, check whether the key is expired, delete the key if it expires, and return the key if it does not expire.
Delete periodically: the program checks the database at regular intervals and deletes the expired keys
2. The elimination strategy of Redus
When the redis in-memory dataset size rises to a certain size, the data elimination strategy is implemented. Redis provides 6 data elimination strategies:
Through the elimination strategy, we can also ensure that the cache in Redis is hot data.
A client runs a new command and adds new data. Redi checks the memory usage, and if it is greater than the limit of maxmemory, it will be reclaimed according to the set policy.
Note the six mechanisms here. Volatile and allkeys specify whether to phase out data from a dataset with an expiration time or from all datasets, and the following lru, ttl, and random are three different phase-out strategies, plus a no-enviction never recycling strategy.
Use policy rules: if the data shows a power-law distribution, that is, some data access frequency is high and some data access frequency is low, then use allkeys-lru; if the data is evenly distributed, that is, all data access frequencies are the same.
Allkeys-random
3. Implementation of Redis distributed lock.
The distributed cache feature of Redis makes it a basic implementation of distributed lock. By whether a lock ID exists in the Redis, you can determine whether it is locked or not. In order to ensure the atomicity of judging whether a lock exists and that only one thread acquires the same lock, Redis has SETNX (that is, SET if Note Exists) and GETSET (write new value first, return old value, atomic operation, which can be used to distinguish whether it is the first operation) operation.
(1) about setnx:
Set the value of key to value, if and only if key does not exist, the return value is 1.
If the given key already exists, the setnx does not take any action and the return value is 0.
(2) about set: general operation
Ex seconds-seconds: sets the duration of failure (in seconds)
Px-milliseconds: sets the duration of failure (in milliseconds)
Set value when nx-key does not exist. Return OK for success and nil for failure.
Set value when xx-key exists. Return OK for success and nil for failure.
In order to prevent deadlocks after host downtime or network disconnection, Redis does not have the natural implementation of ZK, and can only rely on setting timeouts to avoid it. So if you use setnx to implement distributed locks, the implementation steps are as follows:
First use setnx to scramble for the lock, and then use expire to add an expiration time to the lock to prevent the lock from forgetting to release.
If the process accidentally crash or restarts maintenance after setnx and before performing expire, you need to combine setnx and expire into one instruction.
The setnx command of Redis is to set key when key does not exist, but setnx can not complete the setting of expire failure duration at the same time, and can not guarantee the atomicity of setnx and expire. We can use the set command to complete setnx and expire operations, and this operation is atomic. An example is as follows:
Case: set name=p7+, failure duration 100s, set 1.1.1.1 nx OK 6379 > set name p7 + ex 100 nx OK 1.1.1.1 ex 6379 > get name "p7 +" 1.1.1.1 nx OK 6379 > ttl name (integer) 94
As you can see from the above, multiple commands are placed in the same redis connection and redis is single-threaded, so the above operation can be seen as a combination of setnx and expire, which is atomic.
4. Reactor mode of Redis
Redis developed a network event handler based on the Reactor pattern, which is called a file event handler. It consists of four parts: multiple sockets, IO multiplexer, file event dispatcher and event handler.
Redis is called a single-threaded model because the consumption of the file event dispatcher queue is single-threaded.
5. Does redis support transaction rollback?
"rollback action is not supported. Redis supports simple transaction mode, which can only be discard, not rollback."
When Redis executes a transaction command, when the command is queued, Redis will check whether the transaction command is correct, and an error will occur if it is not correct. Both previous and subsequent orders are rolled back by the firm and nothing is executed.
When the command format is correct, and because of errors caused by manipulating the data structure, the command execution error occurs, and the commands before and after the command are executed normally. This is very different from the database, which is something to pay attention to.
For some important operations, we must check the correctness of the data through the program to ensure the correct execution of Redis transactions and avoid data inconsistencies. The reason why Redis keeps such a simple transaction is to ensure the performance of the core issue of the mobile Internet.
6. Redis transaction mechanism and CAS
The watch directive provides the behavior of CAS in a redis transaction. In order to detect whether there are conflicts caused by multiple clients changes in the keys of the watch, these keys will be monitored. If at least one monitored key is modified before the exec command is executed, the whole thing will be rolled back, no action will be performed, thus ensuring atomic operation, and the execution of exec will get a reply from null.
7. The difference between Redis and Memcached
Features of Redis:
Fast, because the data is stored in memory, the advantage similar to HashMap,HashMap is that the time complexity of search and operation is O (1).
Support for rich data types, strings, linked lists, hashes, collections and ordered collections
Transactions are supported and operations are atomic. the so-called atomicity is that changes to data are either performed or not performed at all.
Rich features: can be used for caching, messages, set expiration time by key, and will be deleted automatically after expiration
The difference with Memcached is:
Storage mode Memecache stores all the data in memory and will hang up when the power is off. The data cannot exceed the memory size. Part of the Redis is stored on the hard disk, which ensures the persistence of the data.
The data support type Memcache is relatively simple to support data types. Redis has complex data types.
Using the underlying model, the underlying implementation between them and the application protocol for communicating with the client are different.
Redis directly builds its own VM (Virtual Memory) mechanism, because a general system calling system functions (such as java calling its own API) wastes a certain amount of time to move and request.
8. Cache penetration, cache breakdown and cache avalanche
(1) Cache traversal
Query non-existing data, there is no data in the cache, and there is no data in the database. So all requests are accessed to the database, putting pressure on the database. The solution is as follows:
The Bloom filter is used to hash all possible data into a large bitmap, and a certain non-existent data will be intercepted by bitmap, thus avoiding the query pressure on the database.
If the query data is empty, cache the empty data directly and set a short expiration time. In this way, a null value will be returned directly on the next visit.
(2) Cache breakdown
Cache breakdown refers to the excessive pressure on the database when the client queries the same piece of data in an instant after the cache expires. A common practice in the industry is to use mutex. To put it simply, when the cache expires (it is judged that the value taken is empty), it is not necessary to load db immediately.
Instead, use some operations of the cache tool with the return value of successful operation (such as SETNX of Redis or ADD of Memcache) to set a mutex key. When the operation returns successfully,
Then perform the load db operation and reset the cache; otherwise, retry the entire get cache method. Code similar to the following:
Public String get (String key) {String value = redis.get (key); if (value = = null) {/ / indicates the cache value expires / / sets the 3min timeout to prevent the del operation from failing. The next cache expiration cannot be load db if (redis.setnx (key_mutex, 1,3 * 60) = = 1) {/ / indicates a successful setting value = db.get (key) Redis.set (key, value, expire_secs); redis.del (key_mutex);} / / this time means that other threads at the same time have been load db and set back to the cache. / / if you try to get the cache value again, you can else {sleep (50); get (key). / / retry}} else {return value;}}
(3) cache avalanche
Avalanche means that a large number of query requests pour into the system after a large number of hot data in the cache expires, because most of the data has expired in the Redis layer, the requests infiltrate into the database layer, and a large number of requests pour in like a flood, resulting in database pressure, resulting in query congestion or even downtime.
Solution:
Spread the cache expiration time, for example, the expiration time of each key is random, to prevent a large number of data expiration at the same time, so that all requests will not fall on the database layer at the same time. If the cache database is distributed, distribute the hot spot data evenly among different Redis and databases to effectively share the pressure.
Let Redis data never expire (if the business permits).
9. Redis data skew
1. Bigkey exists: the business layer avoids the creation of bigkey, splits the bigkey of collection type into multiple small collections, and stores a large number of collection elements (collection type) in bigkey, which will increase the data volume of this instance and increase memory resource consumption accordingly. The operation of bigkey will generally cause the instance IO thread to block. If the traffic to bigkey is large, it will affect the speed at which other requests on this instance can be processed.
2. Uneven manual distribution of slot: avoid allocating more slot to an instance and migrating slots
3. There is hot data: the multi-copy method with different key prefixes is adopted. We make multiple copies of the hot data and add a random prefix to the key of each copy of the data so that it and the other copy data will not be mapped to the same Slot. In this way, there are multiple copies of hotspot data that can serve the request at the same time, and at the same time, the key of these replicas is different and will be mapped to different Slot. When assigning instances to these Slot, we should also pay attention to assigning them to different instances, so that the access pressure of hot spot data is distributed to different instances. The multi-copy method of hot spot data can only be used for read-only hot spot data. If the hot data is read and written, it is not suitable to use the multi-copy method, because it will bring additional overhead to ensure the data consistency between multiple replicas.
10. Why is the Redis single-threaded model so efficient?
Pure memory operation
The core is IO multiplexing mechanism based on non-blocking
The bottom layer is implemented in C language. generally speaking, the programs implemented in C language are closer to the operating system and the execution speed is relatively faster.
At the same time, single thread also avoids the problem of frequent context switching of multi-thread, and prevents the competition problem that may be caused by multi-thread.
11. Redis do async and delay queues?
Generally, list structure is used as a queue, rpush produces messages, and lpop consumes messages. When there is no message from lpop, sleep appropriately and try again later. What if the other party asks if you can not use sleep? list also has an instruction called blpop, which will block until the message arrives when there is no message. What if the opposite party asks whether it can be produced and consumed many times at a time? Using the pub/sub topic subscriber mode, you can implement message queuing for 1VR N.
Using zset (ordered set), the timestamp is taken as score, the message content is called zadd as key to produce the message, and the consumer uses the zrangebyscore instruction to obtain the data polling before N seconds for processing.
12. Redis's cluster strategy
(1) the master-slave structure of Redis master-slave synchronization Redis: one master-slave structure, one master-multi-slave structure or cascade structure. The replication type can be divided into full synchronization and incremental synchronization according to whether it is full or not.
(2) if Redis Sentinel wants to monitor master after master-slave replication, Redis provides a Sentinel mechanism, which means to monitor the running status of Redis system and respond accordingly. Redis Sentinal focuses on high availability and automatically promotes slave to master in case of master downtime and continues to provide services.
(3) Redis Cluster focuses on scalability and uses Cluster for sharding storage when a single redis runs out of memory. In redis-cluster architecture, redis-master nodes are generally used to receive reads and writes, while redis-slave nodes are generally only used for backup. They have the same slot set as the corresponding master. If a redis-master fails unexpectedly, then upgrade its corresponding slave to temporary redis-master.
13. Synchronization mechanism of Redis
Redis can use master-slave synchronization and slave synchronization. In the first synchronization, the master node does a bgsave, and records the subsequent modification operations to the memory buffer. After the completion, the rdb files are synchronized to the replication node. After the replication node accepts, the rdb image is loaded into memory. Notify the master node after the load is completed
The synchronization process is completed by synchronizing the operation records modified during the period to the replication node for playback.
At this point, the study of "what are the high-frequency interview questions for Redis" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.