Redis is a very fire non-relational database, how much fire? As long as an internet company will use it. Redis related questions can be said to be the interview must ask, below I from the personal experience as an interviewer, summed up a few must master the knowledge points.
Description: Redis is an open source non-relational database that is written in ANSI C, adheres to the BSD protocol, supports networks, can be persisted in memory, key-value databases, and provides APIs in multiple languages.
Traditional databases follow ACID rules. The acronym for NOSQL (not just SQL) is a general designation of a database management system that differs from a traditional relational database, and generally follows the CAP theorem for distributed distribution.
Github Source: Github.com/antirez/redis
Redis Official website: redis.io/
(
more knowledge points, I put together a mind map, focus on the background to reply to Redis, sent to youWhat is Redis persistence? What kinds of persistence do redis have? What are the pros and cons?
Persistence is the memory data written to disk, to prevent service downtime memory loss.
Redis provides two ways to persist: RDB (default) and AOF
Rdb:
RDB is a redis database abbreviation
function Core function rdbsave (generate RDB file) and rdbload (load memory from file) two functions
AOF:
AOF is the append-only file abbreviation
The Flushappendonlyfile function is called whenever a server (timed) task or function is executed, and the function performs the following two jobs
AoF Write Save:
Write: Writes the cache in Aof_buf to the AoF file, depending on 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 a command text store in the Redis Communication Protocol (RESP) format.
Comparison:
- The aof file is more frequent than the RDB update, and the data is restored with AOF preference.
- AOF is safer and bigger than an RDB.
- RDB performance is better than aof
- If two are equipped with a priority load AOF
Just above you mentioned Redis Protocol (RESP), can explain what is RESP? What are the characteristics?
(You can see a lot of interviews are actually serial guns, the interviewer is actually waiting for you to answer this point, if you answered the comments on you added another point)
RESP is a communication protocol used before the Redis client and server;
Features of RESP:
Simple, fast parsing and 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 schema patterns for Redis? Talk about the characteristics of each
Stand-alone version
Features: Simple
Problem:
1, memory capacity is limited 2, processing capacity is limited 3, can not be highly available.
Master-slave replication
The Redis Replication (replication) feature allows the user to create as many replicas of the server as a Redis server, where the server being replicated is the primary 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, the primary server will always be on their own data updates synchronized to the slave server, thus ensuring that the master-slave server data is the same.
Characteristics:
- Master/slave role
- Master/slave data is the same
- Lower master read pressure in transfer from library
Problem:
- No guarantee of high availability
- does not solve the pressure of master writing
Sentinel
Redis Sentinel is a distributed system that monitors Redis master-slave servers and automatically fails over when the primary server is offline. Three of these features:
Monitoring (Monitoring): Sentinel will constantly check whether your primary server and slave server are functioning properly.
Reminder (Notification): When a problem occurs with a Redis server being monitored, Sentinel can send notifications to administrators or other applications through the API.
Automatic failover (Automatic failover): Sentinel starts an automatic failover operation when a primary server is not working properly.
Characteristics:
- Guaranteed High Availability
- Monitoring individual nodes
- Automatic fault migration
Cons: Master-slave mode, switching takes time to lose data
does not solve the pressure of master writing
Cluster (proxy type):
Twemproxy is a Twitter open source, a redis and memcache fast/lightweight proxy server; Twemproxy is a fast single-threaded agent that supports Memcached ASCII protocol and Redis protocol.
Characteristics:
- Multiple hash algorithms: MD5, CRC16, CRC32, crc32a, Hsieh, Murmur, Jenkins
- Supports automatic deletion of failed nodes
- Backend sharding shard Logic is transparent to the business, read and write to the business side and operate on a single Redis consistent
Disadvantages:
- A new proxy is added and needs to be maintained for its high availability.
- Failover logic needs to be implemented by itself, it can not support the failure of automatic transfer scalability poor, the expansion of the capacity of the need for manual intervention
Cluster (direct-attached):
After Redis 3.0, the Redis-cluster cluster is supported, the Redis-cluster is in a non-central structure, each node holds the data and the entire cluster state, and each node is connected to all other nodes.
Characteristics:
- There is no central architecture (there is no node that affects performance bottlenecks), and the proxy layer is missing.
- Data is distributed in multiple nodes according to slot storage, data sharing between nodes, and data distribution can be adjusted dynamically.
- scalability, scales linearly to 1000 nodes, and nodes can be dynamically added or removed.
- High availability, the cluster is still available when some nodes are unavailable. Make a copy of backup data by adding Slave
- To realize automatic fault failover, the nodes Exchange status information through gossip protocol, and the role of slave to Master is improved by voting mechanism.
Disadvantages:
- The resource isolation is poor, it is prone to mutual influence situation.
- Data is replicated asynchronously and does not guarantee strong data consistency
What is a consistent hashing algorithm? What is a hash slot?
These two questions are too long online to find a good two unlocked articles
Www.cnblogs.com/lpfuture/p/5796398.html
79121213
What type of data does Redis support?
- String strings:
Format: Set key value
The string type is binary safe. This means that a Redis string can contain any data. For example, JPG images or serialized objects.
The string type is the most basic data type of Redis, and a key can store up to 512MB.
Hash (hashed)
Format: Hmset name Key1 value1 key2 value2
A Redis hash is a key-value (Key=>value) pair collection.
Redis Hash is a string-type field and value mapping table, and hash is particularly useful for storing objects.
- List (lists)
The Redis list is a simple list of strings, sorted by insertion order. You can add an element to the head of the list (to the left) or to the tail (to the right)
Format: Lpush Name value
Adds a string element to the head of the list in key
Format: Rpush Name value
Add a string element at the end of the key corresponding list
Format: Lrem name index
Key corresponds to the list to remove count and value elements of the same
Format: Llen name
Returns the length of the key corresponding to the list
- Set (SET)
Format: Sadd Name value
Redis's set is an unordered collection of type string.
The collection is implemented by a hash table, so the complexity of adding, deleting, and finding is O (1).
- Zset (sorted set: Ordered set)
Format: Zadd Name score Value
Redis Zset and set are also collections of string-type elements and do not allow duplicate members.
The difference is that each element is associated with a double-type fraction. Redis is a small-to-large ordering of the members in a collection by fractions.
Zset members are unique, but fractions (score) can be duplicated.
Redis is based on the CAP theory, what is cap theory?
You can refer to my previous article.
If someone asks you what the CAP theory is, send him the article.
Redis common commands?
- Keys pattern
Represents a zone with all
Starting with a bit
See if exists key exists
- Set
Sets the value of the key corresponding to string type.
- Setnx
Sets the value of the key corresponding to string type. If key already exists, returning 0,nx is the meaning of not exist.
Delete a key
First return 1 deleted the second return 0
- Expire
Set expiration time (in seconds)
- Ttl
See how much time is left
- Setex
Set the value of the key to a string type of value and specify the validity period for this key value.
- Mset
Setting the value of multiple keys at once, successfully returning OK means that all values are set, and a failure return of 0 means that no value is set.
- Getset
Sets the value of key and returns the old value of key.
- Mget
Gets the value of more than one key at a time, and returns nil if the corresponding key does not exist.
- Incr
Make a Gaga operation on the value of key and return the new value. Note INCR A value that is not an int returns an error incr a nonexistent key, setting key to 1
- Incrby
Similar to INCR, plus the specified value, key does not exist when the key is set, and the original value is considered to be 0
- Decr
The value of the key is a decrement operation, decr a key does not exist, then set key to 1
- Decrby
With DECR, minus the specified value.
- Append
Appends value to the string value of the specified key, returning the length of the new string value.
- Strlen
Takes the length of the value of the specified key.
- Persist
Cancel Expiration Time
- Select
Select Database
- Randomkey
Randomly returns a key
- Rename
Renaming
- Type
Return data type
Have you ever used a Redis distributed lock, and how does it work?
First take SETNX to grab the lock, after the grab, then use expire to lock plus an expiration time to prevent the lock forgot to release.
What happens if the process unexpectedly crash or restarts maintenance before expire is executed after setnx?
The set directive has very complex parameters, which should be used to synthesize setnx and expire as an instruction!
Do you use Redis as an asynchronous queue? What are the drawbacks?
Generally use the list structure as a queue, Rpush production messages, Lpop consumer messages. When Lpop has no message, try again with a proper sleep.
Disadvantages:
In the case of the consumer offline, the production of the message will be lost, the use of professional Message Queuing such as RABBITMQ.
Is it possible to produce a single consumption multiple times?
With the Pub/sub theme subscriber pattern, you can implement 1:N Message Queuing.
What is cache penetration? How to avoid it? What is a cache avalanche? How to avoid?
Cache penetration
The general cache system is to follow the key to cache the query, if there is no corresponding value, it should go to the backend system lookup (such as DB). Some malicious requests will deliberately query the nonexistent key, the volume of the request is very large, it will cause great pressure on the back-end system. This is called cache penetration.
How to avoid it?
1: The case of NULL query results is also cached, the cache time is set a little bit shorter, or the key corresponding to the data insert after the cache cleanup.
2: Filter The key that does not exist. All possible keys can be placed in a large bitmap, which is filtered by the bitmap when queried.
Cache avalanche
When a cache server restarts or a large number of caches fail at a certain time period, this can put a lot of pressure on the backend system when it fails. Cause the system to crash.
How to avoid it?
1: After the cache fails, the number of threads that read the database write cache is controlled by a lock or queue. For example, a key allows only one thread to query the data and write the cache, and other threads wait.
2: Do two-level cache, A1 for the original cache, A2 for the copy cache, A1 failure, can access A2,A1 cache expiration time set to short-term, A2 set to long-term
3: Different key, set different expiration time, so that the time of cache failure is as uniform as possible.
Well, I wish you all the best interview! Take out a mobile phone to sweep attention ~ irregular delivery of books