In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
Today, I will talk to you about the common interview questions about Redis, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Introduction: Redis is an open source log database written in ANSI C language, complies with BSD protocol, supports network, can be memory-based and persistent, and provides API non-relational database in multiple languages.
Traditional databases follow ACID rules. Nosql (abbreviation of Not Only SQL, which is a general term for database management systems different from traditional relational databases) is generally distributed and distributed generally follows the CAP theorem.
Github source code: https://github.com/antirez/redis
Redis official website: https://redis.io/
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.
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:
1. Aof files are updated more frequently than rdb, so aof is preferred to restore data.
2. Aof is safer and bigger than rdb
3. The performance of rdb is better than aof
4. 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
What are the architectural patterns of Redis? Tell me about their respective characteristics.
Standalone version
Features: simple
Question:
1. Limited memory capacity 2, limited processing capacity 3, can not 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:
1. Master/slave role
2. Master/slave data is the same.
3. 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:
1. Ensure high availability
2. Monitor each node
3. 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: 1. Multiple hash algorithms: MD5, CRC16, CRC32, CRC32a, hsieh, murmur, Jenkins
2. Support automatic deletion of failed nodes
3. The back-end Sharding sharding logic is transparent to the business, and the reading and writing mode of the business side is the same as that of a single Redis.
Cons: 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:
1. No central architecture (there is no bottleneck of which node affects the performance), without proxy layer.
2. The data is distributed in multiple nodes according to slot storage, and the data is shared among nodes, and the data distribution can be adjusted dynamically.
3. Scalability, which can be extended linearly to 1000 nodes, and nodes can be added or deleted dynamically.
4. High availability. When some nodes are unavailable, the cluster is still available. Make backup data copy by adding Slave
5. Realize automatic fault failover, exchange status information between nodes through gossip protocol, and use voting mechanism to upgrade the role from Slave to Master.
Disadvantages:
1. The isolation of resources is poor, and it is easy to influence each other.
2. Data is replicated asynchronously, which does not guarantee the strong consistency of the data.
What is a consistent hash algorithm? What is a hash slot?
Redis common commands?
Keys pattern
* indicates that it is owned by the district.
Starting with bit
Check whether Exists key exists
Set
Set the value of key to value of type string.
Setnx
Set the value of key to value of type string. If key already exists, returning 0menthnx means not exist.
Delete a key
The first time returned 1 and deleted the second time returned 0
Expire sets the expiration time (in seconds)
TTL to see how much time is left.
If a negative number is returned, key is invalid and key no longer exists.
Setex
Set the value for key to value of type string, and specify the validity period for this key.
Mset
Set multiple key values at a time. A successful return of ok means all values have been set, while a failure return of 0 means no values have been set.
Getset
Sets the value of key and returns the old value of key.
Mget
Get the values of more than one key at a time. If the corresponding key does not exist, nil is returned.
Incr
Add the value of key and return the new value. Note that incr A value that is not int will return an error, and if incr a key that does not exist, set key to 1
Incrby
Similar to incr, with a specified value, key is set when key does not exist, and the original value is considered to be 0
Decr
The value of key is subtracted. If there is no key in decr, set key to-1.
Decrby
Same as decr, minus the specified value.
Append
Appends a value to the string value of the specified key and returns the length of the new string value.
Strlen
Takes the length of the value value of the specified key.
Persist xxx (cancel expiration time)
Select database (0-15 libraries)
Select 0 / / Select database
Move age 1max / move age to 1 library
Randomkey randomly returns a key
Rename renaming
Type returns data type
08
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!
09
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.
ten
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?
1: cache the case where the query result is empty, set the cache time to be shorter, or clean the cache after the data corresponding to the key has been insert.
2: 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?
1: 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.
2: do the secondary cache. A1 is the original cache, A2 is the copy cache. When A1 fails, you can access the A1 cache with the expiration time set to short-term and A2 to long-term.
3: set different expiration times for different key to make the cache expiration time as uniform as possible.
After reading the above, do you have any further understanding of the common interview questions in Redis? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.