Redis is a very popular non-relational database. How popular is it? Any Internet company will use it. Redis related questions can be said to be the interview must ask, the following FROM my personal experience as an interviewer, summed up a few knowledge points must be mastered.

Redis is an open source non-relational database that uses ANSI C language, complies with BSD protocol, supports network, can be based on memory and persistence logging, key-value database, and provides a variety of language API.

Traditional databases follow the ACID rules. Nosql(short for Not Only SQL, a general term for database management systems that are different from traditional relational databases) is generally distributed and distributed generally follows the CAP theorem.

Making source: https://github.com/antirez/redis

Redis website: https://redis.io/

What data types do Redis support?

String String:

Format: Set key value

The string type is binary safe. The redis string can contain any data. Like JPG images or serialized objects.

The string type is the most basic Redis data type. A key can store up to 512MB of data.

Hash (Hash)

Format: hmset name key1 value1 key2 value2

A Redis hash is a set of key=value pairs.

Redis hash is a mapping table of fields and values of string type. Hash is especially suitable for storing objects.

The List (List)

A Redis list is a simple list of strings, sorted by insertion order. You can add an element to either the head (left) or the tail (right) of the list

Format: lpush name value

Add a string element to the list header corresponding to the key

Format: rpush name value

Add a string element to the end of the list corresponding to the key

Format: LREM name Index

Delete the count and value elements from the list corresponding to key

Format: llen name

Return the length of the list corresponding to the key

Set (Set)

Format: sadd name value

Redis’ Set is an unordered collection of type string.

Collections are implemented by hashing tables, so adding, deleting, and searching are O(1) complexity.

Sorted set zset(sorted set)

Format: zadd name Score value

Redis zset, like set, is a collection of string elements and does not allow duplicate members.

The difference is that each element is associated with a double score. Redis uses scores to sort the members of a collection from smallest to largest.

Members of a Zset are unique, but scores can be repeated.

What is Redis persistence? What persistence methods does Redis have? What are the pros and cons?

Persistence is to write the data in memory to disk to prevent the loss of memory data when the service is down.

Redis provides two types of persistence :RDB(the default) and AOF

RDB:

  


RDB stands for Redis DataBase

Function core functions rdbSave(generate RDB file) and rdbLoad(load memory from file) two functions

AOF:

  


Aof is short for append-only file

The flushAppendOnlyFile function, which is called every time a server (timed) task or function is executed, does two things

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:

Content is redis communication Protocol (RESP) format command text storage.

Comparison:

Aof files are updated more frequently than RDB files. Aof files are used to restore data preferentially.

Aof is more secure and larger than RDB

RDB has better performance than AOF

If both are configured with priority loading AOF

Just now you mentioned redIS communication protocol (RESP), could you explain what RESP is? What are the characteristics?

(As you can see in many interviews, the interviewer is actually waiting for you to get to this point, and if you get to this point, your rating is added.)

  


RESP is a communication protocol used by redis clients and servers.

RESP features:

Simple implementation, fast parsing, good readability

For Simple Strings the first byte of the reply is a “+” 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 $

For Arrays the first byte of the reply is “*” array

What are the architectural patterns of Redis? Talk about their characteristics

Stand-alone version

  


Features: Simple

Question:

1. Limited memory capacity 2. Limited processing capacity 3.

A master-slave replication

  


Redis replication allows users to create as many replicas of a Redis server as they want. The replicated server is the master server and the replicated server is the slave server. As long as the network connection between the master server and the slave server is normal, the master server will always synchronize its data updates to the slave server to ensure that the data on the master server is the same as that on the slave server.

Features:

Master/slave role

The master/slave data is the same

Reduces master read stress during transfer from library

Question:

High availability is not guaranteed

There is no pressure to solve the master write

The sentry

  


Redis Sentinel is a distributed system that monitors primary and secondary Redis servers and automatically fail-over when the primary server goes offline. Three of these features:

Monitoring: Sentinel continuously checks whether your primary and secondary servers are functioning properly.

Notification: Sentinel can send notifications to administrators or other applications via the API when a monitored Redis server has a problem.

Automatic failover: When a primary server fails, Sentinel starts an Automatic failover operation.

Features:

Ensure high availability

Monitor each node

Automatic failover

Disadvantages: In master/slave mode, switching takes time to lose data

There is no pressure to solve the master write

Cluster (Proxy type) :

  


Twemproxy is an open source Redis and Memcache fast/lightweight proxy server for Twitter; Twemproxy is a fast single-threaded proxy that supports Memcached ASCII and Redis protocols.

Features:

Multiple hash algorithms: MD5, CRC16, CRC32, CRC32a, Hsieh, Murmur, and Jenkins

Failed nodes can be automatically deleted

The back-end Sharding Sharding logic is transparent to services, and the business side reads and writes in the same way as the operation of a single Redis

Disadvantages:

A new proxy is added to maintain its high availability.

The failover logic must be implemented by itself. It cannot automatically transfer faults. The scalability is poor, and manual intervention is required to expand or shrink the capacity

Cluster (direct connection) :

  


Redis 3.0 and later supports redis-cluster clusters. Redis-cluster uses a centrless structure, where each node stores data and the status of the entire cluster, and each node is connected to all other nodes.

Features:

There is no central architecture (no node affecting performance bottlenecks) and no proxy layer.

Data is distributed on multiple nodes based on slot storage. Data is shared among nodes to dynamically adjust data distribution.

Scalability, linear scaling up to 1000 nodes, nodes can be added or removed dynamically.

High availability. The cluster is still available when some nodes are unavailable. Add Slave to make backup data copy

Automatic failover is implemented. Status information is exchanged between nodes through the Gossip protocol. Role promotion from Slave to Master is completed by voting mechanism.

Disadvantages:

Resource isolation is poor, and it is easy to affect each other.

Asynchronous data replication does not ensure strong data consistency

What is a consistent hash algorithm? What is a hash slot?

These two questions are too long and there are two good articles unlocked online

https://www.cnblogs.com/lpfuture/p/5796398.html

https://blog.csdn.net/z15732621582/article/details/79121213

Redis is based on CAP theory. What is CAP theory?

Refer to my last article.

If someone asks you what CAP theory is, send them this article.

Redis common command?

Keys pattern

Indicates that the zone is owned

It starts with bit

Check whether the Exists key Exists

Set

Set the value of key to a string value.

setnx

Set the value of key to a string value. If the key already exists, return 0, nx means not exist.

Delete a key

The first return 1 is deleted and the second return 0

Expire

Setting the expiration time in seconds

TTL

Check how much time is left

Setex

Set the value corresponding to the key to a string value and specify the validity period corresponding to the key value.

Mset

Set multiple key values at once. Ok on success means all values are set, and 0 on failure means none is set.

Getset

Sets the value of key and returns the old value of key.

Mget

Retrieves the value of multiple keys at once, and returns nil if the corresponding key does not exist.

Incr

Add to key and return the new value. Incr a value that is not an int returns an error. Incr a key that does not exist. Set the key to 1

incrby

Similar to incr, if the specified value is not present, the key is set and the original value is assumed to be 0

Decr

Decr if a key does not exist, set the key to -1

Decrby

Same as decr, minus the specified value.

Append

Appends value to the string value specified by 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

Returns a random key

Rename

rename

Type

Return data type

Have you ever used Redis distributed lock and how is it implemented?

Use setnx to fight for locks, and use expire to add an expiration time to locks in case they are forgotten to release.

What happens if a process crashes unexpectedly or needs to restart maintenance after executing EXPIRE after setnx?

The set directive has very complex parameters. It should be possible to combine setnx and EXPIRE into one directive.

Have you ever used Redis for asynchronous queues and how? What are the disadvantages?

The list structure is typically used as a queue, with RPUSH producing messages and LPOP consuming messages. When there are no LPOP messages, sleep for a while and try again.

Disadvantages:

In the event that the consumer goes offline, the production message is lost and a professional message queue such as RabbitMQ is used.

Can we produce once and consume many times?

Using the PUB/SUB topic subscriber pattern, a 1:N message queue can be implemented.

What is cache penetration? How to avoid it? What is cache avalanche? How to avoid it?

The cache to penetrate

General cache systems cache queries based on keys. If there is no corresponding value, go to the back-end system to search for it (such as DB). Some malicious requests intentionally look for nonexistent keys, and the volume of requests can cause a lot of stress on the backend system. This is called cache penetration.

How to avoid it?

1: Cache if the query result is empty, set the cache time to be shorter, or clear the cache after the data corresponding to the key is inserted.

2: Filters non-existent keys. You can put all possible keys into a large Bitmap and filter the query through this Bitmap.

Cache avalanche

When the cache server restarts or a large number of caches fail in a certain period of time, the failure will put a lot of pressure on the backend system. The system crashes.

How to avoid it?

1: Controls the number of threads that can read the database write cache by locking or queuing after the cache is invalid. For example, only one thread is allowed to query data and write to the cache for a key, while the other threads wait.

2: Level 2 cache. A1 is the original cache and A2 is the copy cache. When A1 fails, access A2

3: Set different expiration times for different keys, so that the cache expiration time is as uniform as possible

More content to sort out a brain map, convenient for everyone to remember.

  


All right, good luck with your interview!