If you still don’t understand redis during the interview, take a look at these 40 interview questions (Part 2)

21. What is the master-slave replication model of Redis cluster?

Answer: In order to make the cluster still available when some nodes fail or most nodes cannot communicate, the cluster uses a master-slave replication model, and each node will have N-1 replicas.

22. Will write operations be lost in the Redis cluster? Why?

Answer: Redis does not guarantee strong consistency of data, which means that in practice, the cluster may lose write operations under certain conditions.

23. How are Redis clusters replicated?

Answer: Asynchronous replication

24. What is the maximum number of nodes in a Redis cluster?

Answer: 16,384.

25. How to choose a database for Redis cluster?

Answer: Redis cluster currently cannot select database, and defaults to database 0.

26. How to test the connectivity of Redis?

Answer: Use the ping command.

27. How to understand Redis transactions?

Answer: (1) A transaction is a single isolated operation: all commands in the transaction will be serialized and executed in order. During the execution of the transaction, it will not be interrupted by command requests sent by other clients. (2) A transaction is an atomic operation: either all commands in the transaction are executed, or none of them are executed.

28. What are the commands related to Redis transactions?

答:MULTI、EXEC、DISCARD、WATCH

29. How to set the expiration time and permanent validity of Redis key?

Answer: EXPIRE and PERSIST commands.

30. How does Redis perform memory optimization?

Answer: Use hashes as much as possible. A hash table (that is, the number stored in a hash table is small) uses very small memory, so you should abstract your data model into a hash table as much as possible. For example, if there is a user object in your web system, do not set a separate key for the user's name, surname, email, and password. Instead, store all the user's information in a hash table.

31. How does the Redis recycling process work?

Answer: A client ran a new command and added new data. Redi checks the memory usage. If it is greater than the maxmemory limit, it will be recycled according to the set policy. A new command is executed, etc. So we are constantly crossing the boundary of the memory limit by constantly reaching the boundary and then constantly recycling back below the boundary. If the result of a command results in a large amount of memory being used (such as saving the intersection of a large set to a new key), it won't take long for the memory limit to be exceeded by this memory usage.

32. What are some ways to reduce the memory usage of Redis?

Answer: If you are using a 32-bit Redis instance, you can make good use of collection type data such as Hash, list, sorted set, set, etc., because usually many small Key-Values ​​can be stored together in a more compact way.

33. What happens when Redis runs out of memory?

Answer: If the set upper limit is reached, the Redis write command will return an error message (but the read command can still return normally.) Or you can use Redis as a cache to use the configuration elimination mechanism. When Redis reaches the memory upper limit, the old ones will be flushed. content.

**34. How many keys can a Redis instance store at most? ****List, Set, Sorted Set How many elements can they store at most? **A: Theoretically, Redis can handle up to 2^32 keys, and has been tested in practice. Each instance stores at least 250 million keys. We are testing some larger values. The official FAQ explains that theoretically List, Set, and Sorted Set can hold 2^32 elements. In other words, the storage limit of Redis is the amount of memory available in the system.

35. There are 20 million data in MySQL, but only 20 million data are stored in redis. How to ensure that the data in redis are hot data?

Answer: When the size of the Redis memory data set increases to a certain size, the data elimination strategy will be implemented. Related knowledge: **Redis provides 6 data elimination strategies: **volatile-lru: select the least recently used data from the data set (server.db[i].expires) with an expiration time set to eliminate volatile-ttl: from Select the data to be expired from the data set (server.db[i].expires) with an expiration time set to eliminate volatile-random: Select any data from the data set (server.db[i].expires) with the expiration time set Eliminate allkeys-lru: Select the least recently used data from the data set (server.db[i].dict) Eliminate allkeys-random: Select any data from the data set (server.db[i].dict) Eliminate no- enviction (eviction): prohibit the eviction of data

36. What scenario is Redis most suitable for?

1) Session Cache One of the most commonly used scenarios for using Redis is session cache. The advantage of using Redis to cache sessions over other storage (such as Memcached) is that Redis provides persistence. When maintaining a cache that does not strictly require consistency, most people would be unhappy if all the user's shopping cart information was lost. Now, would they still be? Fortunately, as Redis has improved over the years, it's easy to figure out how to properly use Redis to cache session documents. Even the well-known commercial platform Magento provides plug-ins for Redis.

2) Full page cache (FPC) In addition to the basic session token, Redis also provides a very simple FPC platform. Back to the consistency issue, even if the Redis instance is restarted, users will not see a drop in page loading speed because of disk persistence. This is a great improvement, similar to PHP local FPC. Taking Magento as an example again, Magento provides a plugin to use Redis as a full page cache backend. In addition, for WordPress users, Pantheon has a very good plug-in wp-redis, which can help you load the pages you have browsed as quickly as possible.

3) One of the great advantages of Queue Redis in the field of memory storage engines is that it provides list and set operations, which allows Redis to be used as a good message queue platform. The operations used by Redis as a queue are similar to the push/pop operations of local programming languages ​​​​(such as Python) on lists. If you quickly search "Redis queues" in Google, you will immediately find a large number of open source projects. The purpose of these projects is to use Redis to create very good back-end tools to meet various queue needs. For example, Celery has a backend that uses Redis as the broker. You can view it from here.

4) Ranking list/counter Redis implements the operation of incrementing or decrementing numbers in memory very well. Sets and Sorted Sets also make it very simple for us to perform these operations. Redis just provides these two data structures. So, to get the top 10 users from the sorted set – let’s call them “user_scores”, we just need to do it like this: Of course, this assumes you’re doing it based on your user’s scores Increasing sorting. If you want to return the user and the user's score, you need to execute it like this: ZRANGE user_scores 0 10 WITHSCORES Agora Games is a good example, implemented in Ruby, and its rankings use Redis to store data, you can here See.

5), publish/subscribe Last (but certainly not least) is the publish/subscribe function of Redis. There are indeed many use cases for publish/subscribe. I've seen people use it in social networking connections, as triggers for publish/subscribe based scripts, and even to build chat systems using Redis' publish/subscribe functionality!

37. Suppose there are 100 million keys in Redis, and 100,000 keys start with a fixed, known prefix. How to find them all?

Answer: Use the keys command to scan out the key list of the specified mode. The other party then asked: If this redis is providing services to online businesses, what are the problems with using the keys command? At this time you have to answer one of the key features of redis: redis is single-threaded. The keys instruction will cause the thread to block for a period of time, and the online service will pause. The service cannot be restored until the instruction is executed. At this time, you can use the scan command. The scan command can extract the key list of the specified mode without blocking, but there will be a certain probability of duplication. Just do it once on the client, but the overall time spent will be longer than using it directly. keys command length.

38. If there are a large number of keys that need to be set to expire at the same time, what should you generally pay attention to?

Answer: If the expiration time of a large number of keys is set too concentratedly, redis may experience a brief lag at the time of expiration. Generally, a random value needs to be added to the time to make the expiration time spread out.

39. Have you ever used Redis as an asynchronous queue? How did you use it?

Answer: Generally, the list structure is used as the queue, rpush produces messages, and lpop consumes messages. When there is no message from lpop, sleep for a while and try again. What if the other party asks if I can stop sleeping? There is also a command called blpop in list. When there is no message, it will block until the message arrives. What if the other party asks if it can be produced once and consumed multiple times? Using the pub/sub topic subscriber model, a 1:N message queue can be implemented. If the other party asks what are the disadvantages of pub/sub? When the consumer goes offline, the produced messages will be lost, so a professional message queue such as RabbitMQ must be used. If the other party asks how redis implements a delay queue? I guess now you want to beat the interviewer to death if you have a baseball bat in your hand. Why did you ask such detailed questions? But you were very restrained, and then answered calmly: Use sortedset, use the timestamp as the score, and the message content as the key. Call zadd to produce the message. The consumer uses the zrangebyscore instruction to obtain the data polling N seconds ago for processing. At this point, the interviewer has secretly given you a thumbs up. But what he didn’t know was that you were raising your middle finger behind the chair at this moment.

40. Have you ever used Redis distributed lock? What is it?

First use setnx to compete for the lock. After grabbing it, use expire to add an expiration time to the lock to prevent the lock from forgetting to release. At this time, the other party will tell you that your answer is good, and then ask what will happen if the process crashes unexpectedly or needs to be restarted for maintenance before executing expire after setnx? At this time you have to give surprising feedback: Oh, yes, this lock will never be released. Then you need to scratch your head, pretend to think for a moment, as if the next result is your own initiative, and then answer: I remember that the set command has very complicated parameters. This should be able to set setnx and expire at the same time. Combined into one instruction to use! At this time, the other party will smile and start to say silently in his heart: Press, this guy is not bad.

This article is published by OpenWrite, a blog that publishes multiple articles !

OpenAI opens ChatGPT to all users for free. Voice programmers tampered with ETC balances and embezzled more than 2.6 million yuan a year. Spring Boot 3.2.0 was officially released. Google employees criticized the big boss after leaving the company. He was deeply involved in the Flutter project and formulated HTML-related standards. Microsoft Copilot Web AI will be Officially launched on December 1st, supporting Chinese Microsoft's open source Terminal Chat Rust Web framework Rocket releases v0.5: supports asynchronous, SSE, WebSockets, etc. The father of Redis implements the Telegram Bot framework using pure C language code . If you are an open source project maintainer, encounter How far can you endure this kind of response? PHP 8.3 GA
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/5587102/blog/10149562