In the PHP programmer interview, we may also encounter questions about Redis, this article mainly share with you the most common Redis interview questions, hoping to help everyone.
1. What is Redis?
Redis is a high-performance, memory-based Key-value database.
Features of 2.Reids
Redis is essentially a key-value type of in-memory database, much like memcached, where the entire database is loaded in memory for operation, and the database data is periodically flush to the hard disk for storage by asynchronous operations. Because it is pure memory operation, Redis has excellent performance and can handle more than 100,000 read and write operations per second, which is known
The fastest key-value DB possible.
The great feature of Redis is not only performance, but also the greatest charm of redis is the ability to save a variety of data structures, and the maximum limit for a single value is 1GB, unlike memcached, which can only hold 1MB of data, so Redis is used to implement many useful functions. For example, using his list to do FIFO doubly linked list, to achieve a lightweight high-performance elimination
With his set can do high-performance tag system and so on. In addition, Redis can also set expire time for key-value, so it can also be used as a function-enhanced version of the memcached.
The main drawback of Redis is that database capacity is limited by physical memory and cannot be used as a high-performance read-write for massive data, so Redis is the most suitable scenario for high-performance operations and operations with smaller data volumes.
3. What are the benefits of using Redis?
(1) Fast, because the data exists in memory, similar to the advantage of Hashmap,hashmap is that the time complexity of finding and Operating is O (1)
(2) Support rich data type, support string,list,set,sorted Set,hash
(3) Support transactions, operations are atomic, so-called atomicity is to change the data is either all executed, or all do not execute
(4) Rich features: can be used for caching, messages, press key to set the expiration time, after expiration will be automatically deleted
What are the advantages of 4.redis compared to memcached?
(1) memcached All values are simple strings, redis as its replacement, supports richer data types
(2) Redis is much faster than memcached (3) Redis can persist its data
What are the differences between 5.Memcache and Redis?
1), storage mode Memecache all the data in memory, the power loss will hang, the data can not exceed the memory size. Redis is partially present on the hard drive, which guarantees the data's durability.
2), data support type Memcache is relatively simple for data type support. Redis has complex data types.
3), using the underlying model differs from the underlying implementation between them and the application protocol that communicates with the client. Redis builds its own VM mechanism directly, because the normal system calls system functions, it wastes a certain amount of time to move and request.
6.redis Common performance issues and solutions:
1). Master Write memory snapshot, save command dispatch Rdbsave function, will block the work of the main thread, when the snapshot is large, the performance impact is very large, will intermittently pause service, so master should not write memory snapshot.
2). Master AoF Persistence, if you do not rewrite the aof file, the performance impact of this persistence is minimal, but the aof file will continue to grow, aof file over the General Assembly to affect the recovery speed of master restart. Master should not do any persistent work, including memory snapshots and aof log files, especially do not enable memory snapshots for persistent
If the data is critical, a slave turns on aof backup data, and the policy is synchronized once per second.
3). Master calls bgrewriteaof rewrite aof file, aof in the time of rewriting will occupy a large amount of CPU and memory resources, resulting in service load is too high, there is a short service pause phenomenon.
4). Redis Master-slave replication performance issues, for master-slave replication speed and connection stability, slave and master preferably in the same LAN
7. MySQL has 2000w data, only 20w of data in Redis, how to ensure that the data in Redis are hot data
Related knowledge: When the Redis memory dataset size rises to a certain size, it will implement a data-retirement strategy (recycling strategy). Redis offers 6 kinds of data-culling strategies:
VOLATILE-LRU: Pick the least recently used data from the set of data sets (Server.db[i].expires) that have expired time
Volatile-ttl: Select the data that will expire from the set of expired data sets (Server.db[i].expires)
Volatile-random: Choose data culling from any data set (Server.db[i].expires) that has an expiration time set
ALLKEYS-LRU: Pick the least recently used data culling from the dataset (Server.db[i].dict)
Allkeys-random: Choose data culling from data set (SERVER.DB[I].DICT)
No-enviction (expulsion): Prohibition of eviction data
8. Please use Redis and any language to implement a malicious login protection code, limit 1 hours per User ID can only log in 5 times. The specific login function or function with empty function can not be written in detail.
Implemented in list: Each element in the list represents the login time, so long as the last 5th time and the current difference is not more than 1 hours. The code written in Python is as follows:
#!/usr/bin/env python3import redis import sys import time r = Redis. Strictredis (host= ' 127.0.0.1′, port=6379, db=0) try: id = sys.argv[1]except: print (' Input argument error ' ) sys.exit (0) if R.llen (ID) >= 5 and Time.time () –float (R.lindex (ID, 4)) <= 3600: print ("You are forbid Den logining ") Else: print (' allowed to login ') R.lpush (ID, time.time ()) # Login_func ()
9. Why does Redis need to put all the data in memory?
Redis reads the data into memory for the fastest read-write speed and writes the data asynchronously to disk. So Redis has the characteristics of fast and data persistence. If you do not put the data in memory, the disk I/O speed severely affects the performance of Redis. With memory getting cheaper today, Redis will be more and more popular.
If you set the maximum amount of memory used, you cannot continue inserting new values after the data has reached the memory limit.
10.Redis is single-process one-thread
Redis leverages queue technology to turn concurrent access into serial access, eliminating the overhead of traditional database serial control
11.redis How to solve the problem of concurrent competition?
Redis is a single-process single-threaded mode that uses queue mode to turn concurrent access into serial access. Redis itself does not have the concept of locking, and Redis does not compete for multiple client connections, but there are issues such as connection timeouts, data conversion errors, blocking, and client shutdown connections when Jedis clients have concurrent access to Redis, all of which are
Caused by client connection confusion. There are 2 ways to fix this:
1. Client angle, in order to ensure the normal and orderly communication between each client and Redis, the connection is pooled, while the client read and write Redis operation using internal lock synchronized.
2. Server angle, use SETNX to implement the lock.
Note: For the first, you need the application to handle the synchronization of resources, you can use the method is more popular, you can use synchronized can also use lock, the second need to use the Redis setnx command, but need to pay attention to some problems.
12.redis understanding of Things CAS (Check-and-set operation for optimistic locking)?
Like many other databases, Redis also provides a transactional mechanism as a NoSQL database. In Redis, the multi/exec/discard/watch of these four commands is the cornerstone of our implementation of a transaction. I believe that this concept is not unfamiliar to developers with relational database development experience, and even so, we will briefly list
In Redis
Implementation characteristics of the transaction:
1). All commands in a transaction will be executed serially, and Redis will no longer provide any service for requests from other clients during transaction execution, thus guaranteeing that all commands in the thing are executed atomically.
2). Compared to transactions in a relational database, if a single command fails to execute in a Redis transaction, subsequent commands are still executed.
3). We can start a transaction with the Multi command, and someone with a relational database development experience can interpret it as a "BEGIN TRANSACTION" statement. The commands executed after the statement are treated as operations within the transaction, and finally we can commit/rollback all operations within the transaction by executing the Exec/discard command. These two
A Redis command can be considered equivalent to a commit/rollback statement in a relational database.
4). Before the transaction is opened, if there is a communication failure between the client and the server and causes the network to disconnect, then all statements to be executed will not be executed by the server. However, if a network outage event occurs after the client executes the EXEC command, all commands in the transaction are executed by the server.
5). When using append-only mode, Redis writes all writes within the transaction to disk in this call by calling the system function write. However, if a system crash occurs during the write process, such as an outage due to a power failure, then perhaps only some of the data is written to disk, while the other part of the data is lost.
The Redis server performs a series of necessary consistency checks on reboot and, once a similar problem is found, exits immediately and gives the appropriate error prompt. At this point, we need to take full advantage of the REDIS-CHECK-AOF tools available in the Redis Toolkit, which can help us navigate to errors that are inconsistent with the data and write the part
Data to be rolled back. After the repair, we can restart the Redis server again.
13.WATCH commands and CAS-based optimistic locking:
In a redis transaction, the Watch command can be used to provide CAS (check-and-set) functionality. Suppose we monitor multiple keys before a transaction executes through the Watch command, and if any key value changes after watch, the EXEC command executes the transaction is discarded, and a null Multi-bulk answer is returned to notify the caller of the transaction
Execution failed. For example, once again, we assume that Redis does not provide the INCR command to achieve the atomic increment of the key values, and we can only write the corresponding code ourselves if we want to implement this function. The pseudo code is as follows:
val = GET MyKey
val = val + 1
SET MyKey $val
The above code is guaranteed to be correct only in the case of a single connection, because if more than one client is executing the code at the same time, there is a common error scenario in a multithreaded program-race contention (race condition). For example, both client A and B read the original value of the MyKey at the same time, assuming that the value is 10, and then two clients then add the value one after another set back to the Redis server, which results in a mykey result of 11 instead of 12 as we think. To solve a similar problem, we need the help of the Watch command, as shown in the following code:
WATCH MyKey
val = GET MyKey
val = val + 1
MULTI
SET MyKey $val
Exec
Unlike the previous code, the new code monitors the key with the watch command before it gets the value of MyKey, and then encloses the set command in the transaction, which effectively guarantees that each connection is executed before exec, if the value of the MyKey that is obtained by the current connection is modified by the other connected clients. The EXEC command that is currently connected will fail to execute. This allows the caller to know if the Val has been reset successfully after judging the return value.
Several ways to 14.redis persistence
1. Snapshot (Snapshots)
By default, Redis stores a snapshot of the data in a binary file on disk, with the file name Dump.rdb. You can configure a Redis persistence policy to write data to disk if the data set has more than m updates per n seconds, or you can manually invoke the command save or Bgsave.
Working principle
. Redis Forks.
. The child process begins writing data to the temporary RDB file.
. When the child process finishes writing the Rdb file, replace the old file with the new file.
. This approach enables Redis to use copy-on-write technology.
2, AOF
The snapshot mode is not very robust, and the data that was written to Redis is lost when the system stops, or if the Redis is accidentally killed. This may not be a big problem for some applications, but for applications that require high reliability,
Redis is not a suitable choice.
Append-only file mode is another option.
You can open the AOF mode in the configuration file
3. Virtual Memory mode
When your key is small and value is large, the effect of using a VM is better. Because this saves more memory.
When your key is not small, consider using some very important methods to turn a large key into a large value, such as you might consider combining key,value into a new value.
Vm-max-threads This parameter, you can set the number of threads to access the swap file, set the best not to exceed the machine's core number, if set to 0, then all the operation of the swap file is serial. This can result in a long delay, but with good assurance of data integrity.
The performance of virtual memory is also good when you test yourself. If you have a large amount of data, consider a distributed or other database
15.redis Cache invalidation policy and primary key invalidation mechanism
As the cache system periodically cleans up invalid data, a primary key invalidation and elimination policy is required.
In Redis, a lifetime key is called volatile. When creating a cache, to set the lifetime for a given key, it may be deleted when the key expires (with a lifetime of 0).
1, affecting the survival time of some operations
The time to live can be removed by using the DEL command to remove the entire key, or by overwriting the original data by the SET and Getset commands, i.e., modifying the value of the key and overwriting it with the same key and value, the current data has a different lifetime.
For example, executing a INCR command on a key, Lpush a command on a list, or executing a hset command on a hash table does not modify the lifetime of the key itself. On the other hand, if a key is renamed with rename, the name of the renamed key is the same as before the change of name.
Another possibility of the rename command is to attempt to rename a key with a time-to-live to another another_key with a time-to-live, when the old Another_key (and its lifetime) is deleted, and the old key is renamed to Another_key, so The new Another_key also has the same survival time as the original key. Using the Persist command, you can remove the key's lifetime without deleting the key, and let the key become a persistent key again.
2, how to update the survival time
You can execute the expire command on a key that already has a time-to-live, and the newly specified time-to-live replaces the old time-to-live. The accuracy of the expiration time has been controlled within 1ms, the time complexity of the primary key failure is O (1),
With the expire and TTL commands, the TTL can be used to see the current lifetime of the key. The setting returns 1 successfully, or 0 if key does not exist or the time to live is not set for key.
Maximum cache configuration
In Redis, allows the user to set the maximum memory size for use
Server.maxmemory
The default is 0, no maximum cache is specified, and if new data is added, exceeding the maximum memory will cause Redis to crash, so be sure to set it up. When the size of the Redis memory dataset rises to a certain size, a data-culling strategy is implemented.
Redis offers 6 kinds of data-culling strategies:
. VOLATILE-LRU: Pick the least recently used data from the set of data sets (Server.db[i].expires) that have expired time
. Volatile-ttl: Select the data that will expire from the set of expired data sets (Server.db[i].expires)
. Volatile-random: Choose data culling from any data set (Server.db[i].expires) that has an expiration time set
. ALLKEYS-LRU: Pick the least recently used data culling from the dataset (Server.db[i].dict)
. Allkeys-random: Choose data culling from data set (SERVER.DB[I].DICT)
. No-enviction (expulsion): Prohibition of eviction data
Note that the 6 mechanisms here, volatile and AllKeys, specify whether to retire data from the set expiration time or retire data from all datasets, and the LRU, TTL, and random are three different elimination strategies. Plus a strategy that no-enviction never recycles.
To use policy rules:
1, if the data display power law distribution, that is, part of the data access frequency, part of the data access frequency is low, then use ALLKEYS-LRU
2, if the data is distributed evenly, that is, all the data access frequency is the same, the use of allkeys-random
Three types of data-retirement strategies:
TTL and random are easier to understand and easier to implement. The most recent use of LRU is the most recently used elimination strategy, the design will be the key by the expiration time, and then take the first invalid key to eliminate
16.redis best-fit scene
Redis is best suited for all data in-momory scenarios, although Redis also provides persistence, but actually more of a disk-backed function, compared to the traditional sense of persistence there is a big difference, then you may have questions, It seems that Redis is more like an enhanced version of memcached, so when to use memcached, when to use Redis?
If you simply compare the differences between Redis and memcached, most of them will get the following ideas:
1, Redis not only supports simple k/v type of data, but also provides the storage of data structures such as List,set,zset,hash.
2, Redis support data backup, that is, Master-slave mode of data backup.
3, Redis support data persistence, you can keep the in-memory data on the disk, restart the time can be loaded again for use.
(1), session cache
One of the most common scenarios for using Redis is the session cache. The advantage of using a Redis cache session over other storage (such as memcached) is that Redis provides persistence. When maintaining a cache that is not strictly consistent, if the user's shopping cart information is lost, most people will be unhappy, now,
Are they going to do this again?
Fortunately, with Redis's improvements over the years, it's easy to find out how to properly use Redis to cache your session's documentation. Even the well-known business platform Magento offers Redis plugins.
(2), full page cache (FPC)
In addition to basic session tokens, Redis offers a simple FPC platform. Back to the consistency issue, even though the Redis instance was restarted, because of the persistence of the disk, the user will not see a drop in page loading speed, which is a great improvement, similar to PHP native FPC.
Again, for example Magento, Magento provides a plug-in to use Redis as the full-page cache backend.
In addition, for WordPress users, Pantheon has a very good plug-in Wp-redis, this plugin can help you to load the fastest speed you have visited the page.
(3), queue
One of the great advantages of Reids in the memory storage engine area is the provision of list and set operations, which enables Redis to be used as a good Message Queuing platform. The operation that Redis uses as a queue is similar to the push/pop operation of a local program language (such as Python) on a list.
If you quickly search for "Redis queues" in Google, you'll soon be able to find lots of open source projects that are designed to use Redis to create very good back-end tools to meet a variety of queue requirements. For example, celery has a background where redis is used as a broker, which you can view from here.
(4), leaderboard/Counter
Redis's operation of incrementing or decreasing numbers in memory is very well implemented. The set (set) and the ordered set (Sorted set) also make it very simple to perform these operations, and Redis just provides the two data structures exactly. So, we're going to get the top 10 users from the sorted collection – we
Called "User_scores", we just need to execute as follows:
Of course, it is assumed that you are doing an incremental sort based on your user's score. If you want to return users and users ' scores, you need to do this:
Zrange User_scores 0 Withscores
Agora Games is a good example of what you can see in Ruby, which uses Redis to store data.
(5), Publish/Subscribe
Last (but certainly not least) is the Publish/Subscribe feature of Redis. There are really a lot of usage scenarios for publish/subscribe. I've seen people use it in social networking connections, as a publish/subscribe-based scripting trigger, and even use Redis's publish/Subscribe feature to build chat systems! (No, it's true, you can go to the nuclear
Real).
All of the features that Redis offers, I feel this is the least of the people who like it, although it provides users with this versatility.
Related recommendations:
The Redis in PHP is detailed
Examples of applications for Redis in PHP
Common usage scenarios for Redis sharing