Redis high-frequency interview questions (2023 latest)

Preface

I won’t go into too much detail, because it’s an interview question, so just memorize it and you’ll be ok. It’s guaranteed to make you happy for two and a half years.
Java's latest interview questions (java basics, collections, multi-threading, jvm, locks, algorithms, CAS, Redis, database, mybatis, spring, springMVC, springBoot, microservices)

1.What is redis

It is a high-performance non-relational database developed in C language.

2.What are the storage structures of redis?

String: key-value pair. Application scenarios: caching, SMS verification code, etc.

set key value  //设置值
get key        //获取值

Hash: key-value pair, which can store multiple key-value pairs and is suitable for storing objects. Application scenarios: caching, etc., more space-saving than String.

hset key field value //设置值
hget key field       //获取值

List: equivalent to a linked list. Application scenarios: message queue, etc.

LPUSH key  element1 element2 element3 ...   //左边插入元素,头插法
LPOP key                                    //移除并返回列表左侧的第一个元素,没有则返回nil

Set: Similar to HashSet, unordered and non-repeatable. Application scenarios: mutual friends, etc.

SADD key member1 member2 member3 ...  //向set中添加一个或多个元素
SREM key member1   //移除set中的指定元素

Zset: similar to TreeSet, non-repeatable, has a weight parameter, sort according to this. Application scenario: ranking list.

ZADD key score1 member1 score2 member2 score3 member3  //添加一个或多个元素到sorted set ,如果已经存在则更新其score值
ZREM key member1                                       //删除sorted set中的一个指定元素

3. Why should we use redis and why is redis so fast?

① Memory operation, fast. Read 110,000 times per second and write 80,000 times.
②Support transactions and persistence.
③Single thread, avoiding thread switching. Redis 6 introduces multi-threading.
④ Use IO multiplexing to process multiple connection requests in a single thread.

4. Cache avalanche, cache penetration, cache breakdown

Cache avalanche: A large number of data in the cache expires, and then a large number of requests are made to access the database, causing excessive pressure on the database or downtime. Or redis is down.
Solution:
① Make the cache expiration time distribution more even.
②Set up a high-availability cluster.

Cache penetration: Neither the cache nor the database has the required data, and requests will continue to be made, putting pressure on the database.
Solution:
①Set a null value or default value for the cache.
②Use Bloom filter. First use the filter to determine whether the data exists, and then continue to search if it exists.

Cache breakdown: A certain key expires, and there happens to be a large number of requests to access this key, which causes excessive pressure on the database.
Solution:
① Use a mutex lock to only allow one request to access, then bring the data to the cache, and then access the request for the remaining requests.
② Set the cache not to expire.

5.Redis persistence mechanism

RDB (default): Save memory data to the hard disk in the form of a snapshot (recording data at a certain moment, equivalent to taking a photo) within a certain period of time. Write data to a temporary file at a certain point in time, and then replace the last persisted file.

# 在 10秒之后,如果至少有 1 个 key 发生变化,Redis就会自动创建快照
save 10 1 

Advantages: When recovering large data sets, it is more efficient than AOF.
Disadvantages: unsafe, data loss.

AOF: Each written command will be recorded to the log file (the same log file will not be replaced), and redis restart will restore the persistent log file. If both persistences are enabled, AOF will be restored first.

# 开启 AOF 持久化
appendonly yes  

# 每次有数据修改发生时都会写入 AOF 文件,速度缓慢但是最安全
appendfsync always    

# 每秒钟同步一次,显示地将多个写命令同步到硬盘。AOF 默认使用的
appendfsync everysec  

# 让操作系统决定何时进行同步,速度最快
appendfsync no       

Pros: Safe, almost no data loss.
Disadvantages: AOF files are larger than RDB files and the recovery speed is slow.

6.redis expiration strategy

Scheduled deletion: Each key needs to create a timer, and the key will be cleared when the time is up, so it is very memory-friendly, but it will occupy a lot of CPU resources to handle expiration.
Lazy deletion: When the key is used, it is judged whether it has expired, and then cleared when it expires. This can save CPU resources, but it is not friendly to memory. There may be a large number of expired keys that have not been cleared.
Periodic deletion: a combination of scheduled deletion and lazy deletion. Expired keys are extracted at regular intervals to check whether they have expired (the default is to perform 10 clearings per second, and extract 5 tests each time). If they expire, they will be cleared.

# 1秒检查10次
hz 10 

# 一次抽取的个数,默认是5个
maxmemory-samples 5

7.redis elimination strategy

When the redis memory is full, the memory is eliminated and some keys are deleted. The lfu strategy added in redis 4.0.

# 默认的最大内存设置为1GB
maxmemory 1GB

①volatile-lru: For keys with an expiration time set, use the lru algorithm (least recently used key: based on time) to eliminate them.
②allkeys-lru: Use the lru algorithm for elimination of all keys.
③volatile-lfu: For keys with an expiration time set, use the lfu algorithm (least recently used: according to the counter) to eliminate them.
④allkeys-lfu: Use the lfu algorithm to eliminate all keys.
⑤volatile-random: Use random elimination mechanism to eliminate all keys with expiration time set.
⑥allkeys-random: Use a random elimination mechanism to eliminate all keys.
⑦volatile-ttl: Delete the one with the earliest expiration time (the one with the shortest remaining survival time).
⑧no-eviction (default): Do not delete the key, and the operation will report an error.

8. How to set up high availability or clustering for redis

① Master-slave replication: one master, one or more slaves, and the slave nodes replicate data on the master node. The master node is responsible for writing and the slave node is responsible for reading. It can better share the pressure on the master node, but if the master node goes down, some data will be out of sync.
② Sentinel mode (key point): It is also a master-slave mode. The sentinel queries the host regularly. If the host does not respond for too long, multiple sentinels will vote for a new host. Improved availability, but still cannot work during the election of a new master node.
③Cluster cluster mode: It adopts multi-master and multi-slave (usually three masters and three slaves), and performs sharding according to the rules. Each redis node stores different data, which solves the problem of single-machine storage. Replication and failover capabilities are also provided. Configuration is more troublesome.

9. redis implements distributed locks

Distributed lock: It is an implementation of a lock that controls different processes in a distributed system to jointly access shared resources. Business scenarios such as placing flash sales orders, grabbing red envelopes, etc. all require the use of distributed locks. Redis can be used as a distributed lock.
①Write the commands setnx + expire separately.

setnx key value //新增一个key,key存在返回1,不存在不增加返回0
expire key 100  //key过100秒过期。单位是秒
问题:无法保证原子性,setnx锁了之后,然后出现问题,过期时间没有设置,那么锁就是永久的了(别的线程就永远获取不到锁了)

②The setnx + value value is the expiration time.

setnx key 过期时间  //把过期时间放到value,解决过期时间没有设置的问题,对比过期时间和当前时间就可以知道是否过期。
问题:取当前时间,分布式要求时间同步。

③Use Lua script (including two instructions SETNX + EXPIRE: ensuring atomicity).

④Extended command of set (SET key value[EX seconds][PX milliseconds][NX|XX]).

EX seconds:将键的过期时间设置为 seconds 秒。
PX milliseconds:将键的过期时间设置为 milliseconds 毫秒。
NX:只在键不存在的时候,才对键进行设置操作。SET key value NX 等同于 SETNX key value
XX:只在键已经存在的时候,才对键进行设置操作

set key value ex 10 nx  //key不存在才能新增,并且设置过期时间为10s。
问题:(1) 锁过期释放了,业务还没执行完。a获取锁,执行时间超过10秒,然后被b线程获取锁,导致代码执行顺序不一致。
	 (2)  锁被误删,因为(1),a没执行完释放锁,被b获取,然后a执行完,删除锁,然后b可能还没执行完。

⑤set ex px nx + Verify the unique random value and then delete it.

把 value设置成一个随机数,删除的时候对比随机数,一致再删除。	
问题:还是存在业务没执行完,锁释放。

⑥Open source framework ~Redisson.

方案五还存在业务没执行完,锁释放问题。
Redisson:给获得锁的线程,开启一个定时守护线程,每隔一段时间检查锁是否还存在,存在则对锁的过期时间延长,防止锁过期提前释放。

⑦ Multi-machine distributed lock Redlock. Suppose there are 5 master nodes running on five servers.

按顺序向5个master节点请求加锁
根据设置的超时时间来判断,是不是要跳过该master节点。锁过期时间是10ms,超时时间是20ms,那么就跳过。
如果大于等于3个节点(N/2+1)加锁成功,并且使用的时间小于锁的有效期,即可认定加锁成功啦。
如果获取锁失败,再所有主节点解锁,没获取到锁也会解锁,防止九年义务教育漏网之鱼。

Detailed link

10. Characteristics of distributed locks

Mutual exclusivity: At any time, only one client can hold the lock. Lock
timeout release: When the lock is held, it can be released to prevent unnecessary waste of resources and deadlock.
Reentrancy: if a thread acquires the lock After that, the request can be locked again.
High performance and high availability: locking and unlocking need to be as low-cost as possible, while also ensuring high availability to avoid distributed lock failure.
Security: the lock can only be deleted by the client holding it. , cannot be deleted by other clients

11.Redis application scenarios

① Cache
② Database
③ Ranking list
④ Counter
⑤ Message queue
⑥ Distributed lock
⑦ Shared Session

Guess you like

Origin blog.csdn.net/twotwo22222/article/details/129005575