Redis Is a very popular non relational database , What's the extent of the fire ? Any Internet company will use it .Redis Related questions can be said to be the interview must ask , Below I am from personal experience as an interviewer , Summarize several knowledge points that must be mastered .
introduce :Redis It's an open source use ANSI C Language writing , comply with BSD agreement , Support network , Log type that can be memory based or persistent ,Key-Value
database , It also provides multi lingual API Non relational database of . Traditional database follows ACID rule . and Nosql(Not Only SQL
Abbreviation for , Is different from the traditional relational database database management system ) It is generally distributed, and distributed generally follows CAP theorem .

* String character string : format : set key value
string Type is binary safe . intend redis Of string It can contain any data . such as jpg Images or serialized objects .
string The type is Redis Basic data types , One key can store the most 512MB. Hash( Hash ) format : hmset name key1 value1 key2
value2 Redis hash Is a key value (key=>value) On set . Redis
hash It's a string Type field and value Mapping table for ,hash Especially suitable for storing objects .
* List( list ) Redis A list is a simple list of strings , Sort by insertion order . You can add an element to the head of the list ( left ) Or the tail ( right ) format : lpush
name value stay key corresponding list Add a string element to the header of the format : rpush name value stay key corresponding list
Add a string element to the end of format : lrem name index key corresponding list Delete in count And value Same elements format : llen
* return key corresponding list Length of
* Set( aggregate ) format : sadd name value Redis Of Set yes string An unordered collection of types .
The collection is implemented by hash table , So add , delete , The complexity of the search is O(1).
* zset(sorted set: Ordered set ) format : zadd name score value Redis zset and set
It's the same thing string A collection of type elements , And duplicate members are not allowed .
The difference is that each element is associated with a double Score of type .redis It is through scores that the members of a collection are sorted from small to large .
zset Members of are unique , But the score (score) But it can be repeated .
What is? Redis Persistence ?Redis What are the persistence methods ? What are the advantages and disadvantages ?

Persistence is to write data from memory to disk , Prevent service downtime from memory data loss . Redis Provides two ways to persist :RDB( default ) and AOF RDB:


rdb yes Redis DataBase abbreviation Function core function rdbSave( generate RDB file ) and rdbLoad( Load memory from file ) Two functions  AOF:


* Aof yes Append-only file abbreviation Whenever the server is executed ( timing ) Task or function flushAppendOnlyFile Functions are called ,
This function performs the following two tasks aof Write save : WRITE: According to the conditions , take aof_buf Cache in write to AOF file SAVE: According to the conditions , call fsync or
fdatasync function , take AOF Save the file to disk .  storage structure :  The content is redis Communication protocol (RESP ) Format command text storage .
compare :aof File ratio rdb High update frequency , priority of use aof Restore data .
* aof than rdb It's safer and bigger
* rdb Performance ratio aof good
* If both are configured with priority loading AOF
You mentioned that just now redis Communication protocol (RESP ), Can you explain what it is RESP? What are the characteristics ?

( You can see that many interviews are actually serial , The interviewer is actually waiting for you to answer this point , If you answer the evaluation of you, it will add another point )


* RESP yes redis A communication protocol previously used by the client and the server ; RESP Characteristics of : Easy to implement , Fast analysis , 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 "$" character string
* For Arrays the first byte of the reply is "*" array
Redis What are the architectural patterns ? Talk about their own characteristics

Stand alone version


characteristic : simple problem : 1, Limited memory capacity 2, Limited processing capacity 3, Cannot be highly available . Master slave replication


* Redis Copy of (replication) The function allows the user to set a Redis
Server to create any number of copies of the server , The replicated server is the primary server (master), 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 master server will always update and synchronize the data that happens to itself
To slave server , Thus, the data of master and slave servers are always the same . characteristic :master/slave role
* master/slave The data are the same
* reduce master Read pressure in transfer from library
problem :

* High availability cannot be guaranteed
* It's not solved master The pressure of writing


Redis sentinel Is a distributed system monitoring redis
Master slave server , And it will automatically fail over when the primary server is offline . Three of them : monitor (Monitoring): Sentinel Will constantly check whether your master server and slave server are working properly .

remind (Notification): When someone is being monitored Redis When there is a problem with the server , Sentinel It can be done through API Send a notification to an administrator or other application .

Automatic fault migration (Automatic failover): When a primary server is not working properly , Sentinel An automatic fail over operation is initiated .

characteristic :

* Ensure high availability
* Monitor each node
* Automatic fault migration
shortcoming : Master slave mode , Switching takes time to lose data

It's not solved master The pressure of writing

colony (proxy type ):


Twemproxy It's a Twitter Open source redis and memcache fast / Lightweight proxy server ; Twemproxy
Is a fast single thread agent , support Memcached ASCII Agreement and redis agreement .

characteristic :

* varied hash algorithm :MD5,CRC16,CRC32,CRC32a,hsieh,murmur,Jenkins
* Automatic deletion of failed nodes is supported
* back-end Sharding Slicing logic is transparent to business , The reading and writing mode and operation of business side are single Redis agreement
shortcoming :

* Added new proxy, High availability needs to be maintained .
* failover Logic needs to be realized by itself , It can't support the automatic transfer of failure and has poor scalability , Manual intervention is required for volume expansion and contraction
colony ( Direct connection type ):


from redis
3.0 Later version support redis-cluster colony ,Redis-Cluster No center structure is adopted , Each node holds the data and the entire cluster state , Each node is connected to all other nodes .

characteristic :

* Centreless architecture ( There is no performance bottleneck affected by which node ), less than proxy layer .
* Data according to slot Storage is distributed over multiple nodes , Data sharing between nodes , Dynamic adjustment of data distribution .
* Scalability , It can be linearly extended to 1000 Nodes , Nodes can be added or deleted dynamically .
* High availability , When some nodes are not available , The cluster is still available . By adding Slave Make backup data copy
* Realize fault automation failover, Between nodes through gossip Protocol exchange status information , By voting mechanism Slave reach Master Role Promotion of .
shortcoming :

* Poor resource isolation , It is easy to interact with each other .
* Data is replicated asynchronously , Strong consistency of data is not guaranteed
What is a consistent hash algorithm ? What is hash slot ?

These two questions are too long I found two good articles to unlock on the Internet……

Redis Common commands ?

* Keys pattern Denotes the ownership of regional distribution with bit initial see Exists key Does it exist
* Set set up key The corresponding value is string Type value.
* setnx set up key The corresponding value is string Type value. If key Already exists , return 0,nx yes not exist What do you mean .
Delete a key First return 1 Deleted Second return 0
* Expire Set expiration time ( Unit second )
* TTL See how much time is left
* Setex set up key The corresponding value is string Type value, And specify the validity period for this key value .
* Mset Set multiple at a time key Value of , Successful return ok Indicates that all values are set , Failure Return 0 Indicates that no value has been set .
* Getset set up key Value of , And return key Old value of .
* Mget Get more than one at a time key Value of , If corresponding key non-existent , Then the corresponding return nil.
* Incr Yes key Add the value of , And return the new value . be careful incr One is not int Of value An error is returned ,incr One that doesn't exist
key, Set the key by 1
* incrby with incr similar , Add the specified value ,key It will be set when it does not exist key, And think that the original value yes 0
* Decr Yes key The value of is subtracted ,decr One doesn't exist key, Set the key by -1
* Decrby with decr, Minus the specified value .
* Append Assign to key The string value of is appended value, Returns the length of the new string value .
* Strlen Take designation key Of value The length of the value .
* persist Cancel expiration time
* Select Select database
* Randomkey Returns a random key
* Rename rename
* Type Return data type
Used Redis Distributed lock , How does it work ?

Take it first setnx To fight for the lock , After grabbing , Reuse expire Add an expiration time to the lock to prevent the lock from forgetting to release . 
If setnx After that expire Unexpected process before crash Or restart maintenance , What would happen ?
 set Instructions have very complex parameters , This should be able to simultaneously setnx and expire To compose an instruction for use !

Used Redis Asynchronous queue , How do you use it ? What are the disadvantages ?

General use list Structure as queue ,rpush Production news ,lpop Consumer News . When lpop When there's no news , Be appropriate sleep Try again later . shortcoming :
In the case of consumers offline , Production messages will be lost , You have to use a professional message queue like rabbitmq etc. .  Can it be produced once and consumed many times ?
  use pub/sub Subject subscriber model , It can be realized 1:N Message queuing for .

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

Cache penetration
  General cache system , It's all in accordance with key To cache queries , If there is no corresponding value, You should go to the back-end system to find out ( such as DB). Some malicious requests will deliberately query for nonexistence key, The number of requests is high , It puts a lot of pressure on the back-end system . This is called cache penetration . 
How to avoid it ? 1: If the query result is empty, it is also cached , Set the cache time a little shorter , Or should we key Corresponding data insert Clean up the cache after .
2: Yes, it must not exist key Filter . Can put all possible existence key Put it in a big one Bitmap in , Query through the bitmap filter .  Cache avalanche
  When the cache server restarts or a large number of caches fail in a certain period of time , So, in case of failure , It will put a lot of pressure on the back-end system . Cause the system to crash .  How to avoid it ?

1: After cache failure , Control the number of threads that read and write the database cache by locking or queuing . For example, for someone key Only one thread is allowed to query data and write cache , Other threads wait .
2: Second level cache ,A1 Is the original cache ,A2 Cache for copy ,A1 In case of failure , Can be accessed A2,A1 Cache expiration time is set to short term ,A2 Set to long term
3: different key, Set different expiration times , Make the time point of cache invalidation as even as possible .

It's hard to remember all that , Let's share a summary of the brain map , Convenient for everyone to remember .

Programmer advanced exchange study group :468947140 ( already expired ); Two groups :878249276

Enter the group to obtain the past Java Advanced architecture information , Source code , note , video
Dubbo,Redis,Netty,zookeeper,Spring cloud, Distributed , High concurrency and other architecture technologies