In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "what are the common Redis interview questions". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the common Redis interview questions.
1. What data types are supported by Redis?
String (string)
Format: set key value
The string type is binary safe. It means that the string of redis can contain any data. Such as jpg images or serialized objects.
String type is the most basic data type of Redis, and a key can store 512MB as much as possible.
Hash (hash)
Format: hmset name key1 value1 key2 value2
Redis hash is a collection of key-value pairs (key= > value).
Redis hash is a mapping table for field and value of type string, and hash is particularly suitable for storing objects.
List (list)
The Redis list is a simple list of strings sorted in the order in which they are inserted. You can add an element to the head (left) or tail (right) of the list.
Format: lpush name value
Add a string element to the header of the corresponding list of key
Format: rpush name value
Add a string element to the tail of the corresponding list of key
Format: lrem name index
Delete count and value elements from list corresponding to key.
Format: llen name
Returns the length of the list corresponding to key
Set (collection)
Format: sadd name value
The Set of Redis is an unordered collection of type string.
The collection is implemented through a hash table, so the complexity of adding, deleting, and finding is all O (1).
Zset (sorted set: ordered set)
Format: zadd name score value
Redis zset, like set, is a collection of elements of type string, and duplicate members are not allowed.
The difference is that each element is associated with a score of type double. Redis sorts the members of the collection from small to large by scores.
The members of the zset are unique, but the score can be repeated.
2. What is Redis persistence? What are the persistence methods of Redis? What are the advantages and disadvantages?
Persistence is to write the data in memory to disk to prevent the loss of memory data due to service downtime.
Redis provides two persistence methods: RDB (default) and AOF
RDB:
Rdb is the abbreviation of Redis DataBase.
Function core functions rdbSave (generate RDB file) and rdbLoad (load memory from file) two functions
AOF:
Aof is the abbreviation of Append-only file.
The flushAppendOnlyFile function is called whenever a server (scheduled) task or function is executed, which performs the following two tasks
Aof write Save:
WRITE: writes the cache in aof_buf to the AOF file according to the condition
SAVE: depending on the condition, call the fsync or fdatasync function to save the AOF file to disk.
Storage structure:
The content is the command text storage in redis Communication Protocol (RESP) format.
Compare:
Aof files are updated more frequently than rdb, and aof is preferred to restore data.
Aof is safer and bigger than rdb.
Rdb has better performance than aof.
If both are equipped with priority loading AOF
Just now you mentioned redis Communication Protocol (RESP). Can you explain what RESP is? What are the characteristics? (you can see that many interviews are in fact a chain of fire, and the interviewer is really waiting for you to answer this point. If you answer your evaluation, you will add another point.)
RESP is a communication protocol previously used by redis clients and servers.
The characteristics of RESP: simple implementation, fast parsing and good readability.
For Simple Strings the first byte of the reply is "+" reply
For Errors the first byte of the reply is "-" error
For Integers the first byte of the reply is ":" integer
For Bulk Strings the first byte of the reply is "$" string
For Arrays the first byte of the reply is "*" array
Persistence asks more frequently in the interview, focus on learning, the space is limited, specifically the following articles:
10 minutes to thoroughly understand the persistence mechanism of Redis: RDB and AOF
3. What are the architecture models of Redis? Tell me about their respective characteristics.
Standalone version
Features:
simple
Question:
Limited memory capacity
Limited processing capacity
Cannot be highly available.
Master-slave replication
The replication function of Redis allows users to create any number of replicas of a Redis server, where the replicated server is the master server (master) and the server replica created by replication is the slave server (slave).
As long as the network connection between the master and slave servers is normal, the master and slave servers will have the same data, and the master server will always synchronize the data updates that occur on itself to the slave server, thus ensuring that the data of the master and slave servers are the same.
Features:
Master/slave role
Master/slave data is the same
Reduce the master reading pressure when transferring to the slave library
Question:
High availability cannot be guaranteed
Did not solve the pressure of master writing
Sentinel
Redis sentinel is a distributed system that monitors redis master and slave servers and automatically fails over when the master server goes offline. Three of these features:
Monitoring (Monitoring): Sentinel will constantly check whether your master server and slave server are working properly.
Reminder (Notification): when there is a problem with a monitored Redis server, Sentinel can send notifications to administrators or other applications through API.
Automatic failover (Automatic failover): when a primary server does not work properly, Sentinel starts an automatic failover operation.
Features:
Ensure high availability
Monitor each node
Automatic failover
Disadvantages:
Master-slave mode, switching takes time to lose data
Did not solve the pressure of master writing
Cluster (proxy type)
Twemproxy is a Twitter open source redis and memcache fast / lightweight proxy server; Twemproxy is a fast single-threaded agent that supports Memcached ASCII and redis protocols.
Features:
Multiple hash algorithms: MD5, CRC16, CRC32, CRC32a, hsieh, murmur, Jenkins
Support automatic deletion of failed nodes
The back-end Sharding sharding logic is transparent to the business, and the business side reads and writes in the same way as the operation of a single Redis.
Disadvantages:
A new proxy has been added and its high availability needs to be maintained.
Failover logic needs to be implemented on its own, and it can not support automatic fault transfer. The scalability is poor, and manual intervention is needed for capacity expansion and reduction.
Cluster (directly connected):
From redis 3.0 onwards, redis-cluster clusters are supported. Redis-Cluster uses a non-central structure, each node holds data and the entire cluster state, and each node connects to all other nodes.
Features:
No central architecture (there are no nodes affecting performance bottlenecks), less proxy layer.
The data is distributed in multiple nodes according to slot storage, and the data is shared among the nodes, and the data distribution can be adjusted dynamically.
Scalability, can be linearly extended to 1000 nodes, nodes can be dynamically added or deleted.
High availability, the cluster is still available when some nodes are unavailable. By adding Slave to make backup data copy-to realize automatic fault failover, nodes exchange status information through gossip protocol, and use voting mechanism to upgrade the role from Slave to Master.
Disadvantages:
The isolation of resources is poor, and it is easy to influence each other.
Data is replicated asynchronously, which does not guarantee the strong consistency of the data.
To analyze and build highly available Redis architecture, please refer to:
Analysis and Construction of High availability Redis Service Architecture
4. Have you ever used Redis distributed locks, and how is it implemented?
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.
What if the process accidentally crash or restarts maintenance before executing expire after setnx?
The set instruction has very complex parameters, which should be able to combine setnx and expire into one instruction at the same time!
5. Have you ever used Redis as an asynchronous queue? how do you use it? What are the shortcomings?
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.
Disadvantages:
In the case of consumers offline, the produced messages will be lost, and professional message queues such as rabbitmq will have to be used.
Can it be produced and consumed more than once?
Using the pub/sub topic subscriber mode, you can implement message queuing for 1VR N.
6. What is cache traversal? How to avoid it? What is a cache avalanche? How to avoid it?
Cache penetration
In general, caching systems cache queries according to key. If there is no corresponding value, you should go to the back-end system to find it (such as DB). Some malicious requests will deliberately query the key that does not exist, and the number of requests is large, which will put a lot of pressure on the back-end system. This is called cache traversal.
How to avoid it?
The case where the query result is empty is also cached, and the cache time is set to be shorter, or the data corresponding to the key is insert and then the cache is cleaned.
Filter key that must not exist. You can put all possible key into a large Bitmap and filter through that bitmap when querying.
Cache avalanche
When the cache server restarts or a large number of caches fail in a certain period of time, it will put a lot of pressure on the back-end system. Causing the system to crash.
How to avoid it?
After the cache expires, the number of threads reading the database write cache is controlled by locking or queuing. For example, only one thread is allowed to query data and write cache for a key, while other threads wait.
Do secondary cache. A1 is the original cache and A2 is the copy cache. When A1 fails, you can access the A1 cache with the expiration time set to short-term and A2 set to long-term.
Set different expiration times for different key to make the cache expiration time as uniform as possible.
This is quite common. If you refer to the following in detail, you must be proficient in it:
Redis cache avalanche, cache breakdown, cache penetration and several common cache modes
7. Redis common commands
Management command
# dbsize returns the number of current database key. # info returns the current redis server status and some statistics. # monitor listens in real time and returns all request information received by the redis server. # shutdown saves data synchronization to disk and shuts down the redis service. # config get parameter gets a redis configuration parameter information. (individual parameters may not be available) # config set parameter value sets a redis configuration parameter information. (individual parameters may not be available) # config resetstat resets statistics for the info command. (the reset includes: number of keyspace hits, # keyspace errors, number of processing commands, number of received connections, number of expired key) # debug object key gets the debugging information of a key. # debug segfault creates a server crash. # flushdb deletes all key in the current database. This method will not fail. Use # flushall carefully to delete all key in all databases. This method will not fail. Use with caution
Tool command
# daemon launcher for redis-server:Redis server # redis-cli:Redis command line operation tool. Of course, you can also use telnet to operate the # redis-benchmark:Redis performance test tool according to its plain text protocol to test the read and write performance of Redis on your system and your configuration $redis-benchmark-n 100000-c 50 # simulation sends 100000 SETs/GETs queries by 50 clients at the same time # redis-check-aof: update log check # redis-check-dump: local database check
8.Redis singleton, master-slave mode, sentinel and cluster configuration and their advantages and disadvantages
Redis singleton, master-slave mode, sentinel and cluster configuration and their advantages and disadvantages
9. Why can Redis single thread support high concurrency?
Why does Redis single thread support high concurrency?
10. Common performance problems and solutions of Redis:
1) .Master writes memory snapshots, and the save command dispatches the rdbSave function, which will block the work of the main thread. When the snapshot is relatively large, it will have a great impact on performance and will intermittently suspend the service. Therefore, it is best not to write memory snapshots for Master.
2). Master AOF persistence, if you do not rewrite AOF files, this persistence method will have the least impact on performance, but AOF files will continue to grow, and excessive AOF files will affect the recovery speed of Master restart. It is best for Master not to do any persistence work, including memory snapshots and AOF log files. In particular, do not enable memory snapshots for persistence. If the data is critical, a Slave enables AOF to back up data. The policy is to synchronize once a second.
3) when the .Master calls BGREWRITEAOF to rewrite the AOF file, AOF will take up a lot of CPU and memory resources when rewriting, resulting in high service load and temporary service suspension.
4). Because of the performance problem of master-slave replication, Slave and Master should be in the same local area network for the speed of master-slave replication and the stability of connection.
Redis performance analysis related questions, limited to space, give a link to the article:
Analysis of Redis performance problems (recommended by good articles)
11. How to solve the concurrency competition problem of Redis?
Redis is a single-process single-thread mode, using queue mode to change concurrent access into serial access. Redis itself does not have the concept of lock, and Redis does not compete for multiple client connections, but problems such as connection timeout, data conversion errors, blocking, and client closure occur when Jedis clients access Redis concurrently, all of which are caused by client connection confusion.
From the client point of view, in order to ensure that each client communicates with Redis in a normal and orderly manner, the connection is pooled, and the internal lock synchronized is used to read and write Redis on the client.
From the server point of view, the lock is realized by using setnx.
Note: for the first, the application needs to handle the synchronization of resources on its own, and the methods you can use are more common, you can use synchronized or lock;, the second setnx command that requires Redis, but you need to pay attention to some problems.
12. Talk about the memory elimination strategy of Redis
Straight here: Redis's memory obsolescence strategy
13. The most suitable scene for Redis
Redis is most suitable for all data in-momory scenarios. Although Redis also provides persistence, it is actually more of a disk-backed function, which is quite different from the traditional persistence, so you may have doubts. It seems that Redis is more like an enhanced version of Memcached, so when to use Memcached and when to use Redis?
If you simply compare the difference between Redis and Memcached, most will get the following point of view:
Redis not only supports simple KBE data, but also provides storage of data structures such as list,set,zset,hash.
Redis supports data backup, that is, data backup in master-slave mode.
Redis supports data persistence, which can keep the data in memory on disk and can be loaded and used again when rebooting.
Session caching (Session Cache)
One of the most common scenarios where Redis is used is session caching (session cache). The advantage of caching sessions with Redis over other stores, such as Memcached, is that Redis provides persistence. When maintaining a cache that is not strictly consistent, most people will be unhappy if all the users' shopping cart information is lost. Will they still do so now?
Fortunately, as Redis has improved over the years, it's easy to find out how to properly use Redis to cache session documents. Even the well-known business platform Magento provides plug-ins for Redis.
Full page cache (FPC)
In addition to the basic session token, Redis provides a very simple FPC platform. Back to consistency, even if the Redis instance is restarted, users will not see a drop in page loading speed because of disk persistence, which is a great improvement, similar to PHP native FPC.
Again, take Magento as an example. Magento provides a plug-in to use Redis as the full-page cache backend.
In addition, for WordPress users, Pantheon has a very good plug-in wp-redis, which can help you load the pages you have visited as quickly as possible.
Queue
One of the advantages of Reids in the field of memory storage engines is that it provides list and set operations, which makes Redis a good message queuing platform to use. The operation used by Redis as a queue is similar to the push/pop operation of list by a native program language such as Python.
If you quickly search for "Redis queues" in Google, you will immediately find a large number of open source projects designed to use Redis to create very good back-end tools to meet a variety of queue needs. For example, Celery has a background that uses Redis as broker, which you can check from here.
Ranking / counter
Redis does a great job of incrementing or decrementing numbers in memory. Set and Sorted Set also make it easy for us to perform these operations, and Redis just happens to provide these two data structures. So, we need to get the top 10 users from the sorted set-we call it "user_scores".
Of course, this assumes that you are sorting incrementally according to the scores of your users. If you want to return the user and the user's score, you need to do this: ZRANGE user_scores 0 10 WITHSCORES
At this point, I believe you have a deeper understanding of "what are the common Redis interview questions?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.