<>1. Redis and MySQL The difference between ?
.mysql It's a relational database , and redis yes NOSQL, Non relational database .mysql Persist data to hard disk , Reading data is slow , and redis The data is stored in the cache first , Fast reading speed , But the storage time is limited , Finally, you can choose to persist to the hard disk as needed .
.mysql As a persistent database , Each visit is made on the hard disk I/O operation . Frequent access to the database will take a lot of time to connect to the database repeatedly .redis A large amount of frequently accessed data is stored in the cache , When the browser accesses the data , Access cache first , If you can't access it, you can enter the database again .
<>2.Redis Five data types of ?
a) String type String Add operation ：set
b) hash objects hash Add operation ： hset
c). List object list Add operation ： lpush
d). Collection object set Add operation ：sadd
e). Ordered collection object sorted set Add operation ： zadd
（ Other operations are omitted ）
<>3.Redis How to solve this problem key conflict ?
Zipper method . Another problem can be taken into account in this issue ,HashMap How to solve this problem key Conflicting , The zipper address method is also used . If asked to resolve key What are the other ways of value conflict ? Generally speaking, it is solved key There are two ways to conflict values , One is the open address method , The other is the zipper method .
<>4.Redis Storage mechanism and persistence scheme of ?
First, understand what persistence is ? The first question has already been explained , In short , be similar to MySQL This way of storing data directly to the hard disk is persistence . however Redis You can't copy it SQL Storage method of , The biggest reason is also mentioned ——NoSQL, Which means that there is no such thing as B+ Tree operation .
The first way RDB Persistence strategy . So is it redis Default method for . First store the data in memory , It is triggered once when the data has accumulated to a certain set threshold value DUMP operation , Save changed data into RDB file .
once Redis Abnormal exit , All data that has changed since the last snapshot is lost
The second way ： open AOF Persistence strategy First store the data in memory . open AOF After persistence, each execution changes Redis Commands for data in ,Redis
This command will be written to the hard disk AOF file .AOF Files do not store data , Stored is the executed command .
AOF The most critical configuration is about calling fsync Frequency of appending log files , There are two preset frequencies ,always Add every time a record comes in ,everysecond
Add once per second .（fsync The function writes data from memory to the hard disk ）.
because AOF and RDB The contents of the stored files are not the same ,RDB What's stored is real , Stored data ,AOF It stores a large number of instructions for manipulating data , Once this kind of instruction increases , Will inevitably make AOF Document expansion , So there's a new mechanism ：Rewrite. so-called Rewrite It is to write all the data in the log file to another new log file , But the difference is , In the old log file, the Key Multiple operations for , The operation that only keeps the final value is recorded in the log file , This reduces the size of the log file .
auto-aof-rewrite-percentage 100 （ Triggered when the size of the current write log file accounts for a certain percentage of the initial log file size Rewrite）.
auto-aof-rewrite-min-size 10mb （ This time Rewrite Minimum amount of write data ）.
<>5.Redis Expiration policy for
How to set redis Expiration time of ? The simplest is to use expire key second, There are other ways, of course , such as pexpire key
milliseconds wait ,redis The syntax for viewing expiration times is also simple ,ttl key You can see how much time is left .
How to delete an expired key, The easiest thing to think of is to give it to everyone key All create timers , Automatically delete as soon as the time is up . This method is unreliable , Although it can guarantee every expired key Can be deleted as soon as possible , But creating a timer itself is a project that consumes a lot of resources , So it's not desirable .
redis The built-in policy is called lazy deletion , Also called “ Passive deletion ”.
key Do not delete when expired , Get from database every time key Check if it's overdue , If overdue , Delete , return null.
This method is desirable , But there must be another problem , When using, judge whether it is expired and then delete it , What if I don't use it ?
If a large number of key After the timeout period has expired , For a long time , None of them have been acquired , Then a memory leak may occur
out of memory out of memory, When a program requests memory , There is not enough memory space for it to use , appear out of memory; Memory leak
memoryleak, Refers to the program after the application of memory , Unable to free the requested memory space , A memory leak hazard can be ignored , But the memory leak accumulation is very serious , No matter how much memory , Sooner or later it will be taken up .
The memory overflow is that there is not enough storage memory in the heap space ,GC There is still not enough memory to store the new object , produce OOM error .
Memory leaks are objects that are useless , But it is still GCroot The path that an object can be associated with , No way out GC recovery , But if it accumulates too much, it will cause OOM.
It's still necessary at this time redis Go to active search , So you need to use another strategy ,
Delete periodically . It is also called active deletion .
Delete every once in a while ( stay redis.conf Profile settings hz,1s Refresh frequency ) be overdue key operation
first , to configure redis.conf Of hz option , The default is 10 （ Namely 1 Second execution 10 second ,100ms once , The higher the value, the faster the refresh rate , most Redis The greater the performance loss ）
second , to configure redis.conf Of maxmemory Maximum , When used memory exceeds maxmemory Limited time , The active clean-up policy is triggered . Active cleaning policy is different from active deletion , Try to avoid triggering active cleaning .
The expiration policy of has no effect on persistence . If used RDB, In persistence key Before the expiration date will be detected , overdue key Will not be saved into the file , At the same time from RDB When restoring to the in memory database, it will also detect whether it is expired once .
If used AOF, Because the storage is all instructions , If key be overdue , The program will AOF In addition del instructions . At trigger Rewrite When , Can judge key Is it overdue , overdue key Instructions are not rewritten to AOF In the file .
<>6.Redis Cluster strategy based on ?
redis There are multiple clusters for , But the most powerful is official redis-cluster.
1. Using decentralization , use hash slot mode take 16348 individual hash slot Covering all nodes For each of the stored key value
use CRC16(KEY)&16348=slot Get his counterpart hash slot And visit key When I went to him hash slot Which node is it on
The current access node is then assigned the hash slot To get the data .
2. Voting fault tolerance . The voting fault tolerance mechanism is used to judge whether the node is still working .Redis Each node in the cluster sends to other nodes on time ” Heartbeat ”. When a node does not respond , Then judge the node failure . The request was that more than half of the votes did not respond .
3. In order to solve the node master invalid fail The problem of , Master slave replication policy can be used .
When is the entire cluster unavailable (cluster_state:fail)?
If the cluster is arbitrary master hang up , And the current master No, slave. Cluster entry fail state , It can also be understood as cluster slot mapping [0-16383] Enter when incomplete fail state .
If more than half of the cluster master hang up , Whether or not slave（ from ）, Cluster entry fail state .
Tips:A,B,C The data stored in the three nodes is inconsistent , The integration of the three nodes is the completion of the data . But the primary server A And slave servers a The data stored in the . Architecture details :
(1) be-all redis Nodes are interconnected with each other (PING-PONG mechanism ), Internal use of binary protocol to optimize transmission speed and band wide . (2) Node's fail
It takes effect when more than half of the nodes in the cluster detect failure . (3) Client and redis Node direct connection , There is no need for the middle proxy layer . The client does not need to connect all nodes of the cluster , Connect cluster
Any available node in the
<>7.Redis Is it single threaded ?
redis It's single threaded !
redis The core is If all my data is in memory , I operate in a single thread It's the most efficient , Why? , Because the essence of multithreading is CPU
Simulate the situation of multiple threads , There is a cost to this simulation , It's context switching , For a memory system , It is the most efficient switch without context .redis use single CPU
Bind a piece of memory data , When the data in this memory is read and written many times , It's all in one CPU On the , So it's single threaded . In the case of memory , This is the best plan .
When to use multithreading ?
The answer is ： The lower level of storage and other slow conditions . Like disks