Redis is a very popular non-relational database. How popular is it? Any Internet company will use it. Redis related questions can be said to be the interview must ask, the following FROM my personal experience as an interviewer, summed up a few knowledge points must be mastered. Redis is an open source non-relational database that uses ANSI C language, complies with BSD protocol, supports network, can be based on memory and persistence logging, key-value database, and provides a variety of language API. Traditional databases follow the ACID rules. Nosql (short for Not Only SQL, a general term for database management systems that are different from traditional relational databases) is generally distributed and distributed generally follows the CAP theorem. Making the source code:Github.com/antirez/red…Redis website:redis.io/

What data types do Redis support?

  • String String:

Format: Set Key Value String is binary safe. The redis string can contain any data. Like JPG images or serialized objects. The string type is the most basic Redis data type. A key can store up to 512MB of data.

  • Hash

Format: hmSet Name Key1 Value1 key2 Value2 Redis Hash is a set of key/value pairs. Redis hash is a mapping table of fields and values of string type. Hash is especially suitable for storing objects.

  • List (List)

A Redis list is a simple list of strings, sorted by insertion order. You can add an element to the head (left) or bottom (right) of the list. Rpush name value add a string element to the end of the list corresponding to the key format: lrem name index key delete count elements in the list that are the same as the value format: Llen name Returns the length of the list corresponding to the key

  • Set

Sadd Name Value Redis is an unordered Set of strings. Collections are implemented by hashing tables, so adding, deleting, and searching are O(1) complexity.

  • Sorted set zset(sorted set)

Format: zadd Name Score value Redis Zset is a set of string elements like set and does not allow duplicate members. The difference is that each element is associated with a double score. Redis uses scores to sort the members of a collection from smallest to largest. Members of a Zset are unique, but scores can be repeated.

What is Redis persistence? What persistence methods does Redis have? What are the pros and cons?

Persistence is to write the data in memory to disk to prevent the loss of memory data when the service is down. Redis provides two types of persistence :RDB (the default) and AOFRDB: RDB is the core function of Redis DataBase abbreviation function rdbSave(generate RDB file) and rdbLoad (load memory from file)AOF: The flushAppendOnlyFile function is called every time a server (timed) task or function is executed. This function does the following two things: Depending on the condition, write the cache in aOF_buf to the AOF file SAVE: Depending on the condition, call the fsync or fdatasync function to SAVE the AOF file to disk.Storage structure:Content is redis communication Protocol (RESP) format command text storage. Comparison:

  1. Aof files are updated more frequently than RDB files. Aof files are used to restore data preferentially.
  2. Aof is more secure and larger than RDB
  3. RDB has better performance than AOF
  4. If both are configured with priority loading AOF

Just now you mentioned redIS communication protocol (RESP), could you explain what RESP is? What are the characteristics?

(As you can see in many interviews, the interviewer is actually waiting for you to get to this point, and if you get to this point, your rating is added.) RESP is a communication protocol used by redis clients and servers. RESP features: simple implementation, fast parsing, 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 “:” Integers
  • For Bulk Strings the first byte of the reply is a “$” string
  • For Arrays the first byte of the reply is “*” array

What are the architectural patterns of Redis? Talk about their characteristics

Stand-alone version Features: Simple problems: 1. Limited memory capacity 2. Limited processing capacity 3.

A master-slave replication Redis replication allows users to create as many replicas of a Redis server as they want. The replicated server is the master server and the replicated server is the slave server. As long as the network connection between the master server and the slave server is normal, the master server will always synchronize its data updates to the slave server to ensure that the data on the master server is the same as that on the slave server. Features:

  1. Master/slave role
  2. The master/slave data is the same
  3. Reduces master read stress during transfer from library

Question:

  1. High availability is not guaranteed
  2. There is no pressure to solve the master write

The sentryRedis Sentinel is a distributed system that monitors primary and secondary Redis servers and automatically fail-over when the primary server goes offline. Three of these features:

Monitoring: Sentinel continuously checks whether your primary and secondary servers are functioning properly.

Notification: Sentinel can send notifications to administrators or other applications via the API when a monitored Redis server has a problem.

Automatic failover: When a primary server fails, Sentinel starts an Automatic failover operation.

Features:

  1. Ensure high availability
  2. Monitor each node
  3. Automatic failover

Disadvantages: In master/slave mode, switching takes time to lose data

There is no pressure to solve the master write

Cluster (Proxy type) :

Twemproxy is an open source Redis and Memcache fast/lightweight proxy server for Twitter; Twemproxy is a fast single-threaded proxy that supports Memcached ASCII and Redis protocols.

Features:

  1. Multiple hash algorithms: MD5, CRC16, CRC32, CRC32a, Hsieh, Murmur, and Jenkins
  2. Failed nodes can be automatically deleted
  3. The back-end Sharding Sharding logic is transparent to services, and the business side reads and writes in the same way as the operation of a single Redis

Disadvantages:

  1. A new proxy is added to maintain its high availability.
  2. The failover logic must be implemented by itself. It cannot automatically transfer faults. The scalability is poor, and manual intervention is required to expand or shrink the capacity

Cluster (direct connection) :

Redis 3.0 and later supports redis-cluster clusters. Redis-cluster uses a centrless structure, where each node stores data and the status of the entire cluster, and each node is connected to all other nodes.

Features:

  1. There is no central architecture (no node affecting performance bottlenecks) and no proxy layer.
  2. Data is distributed on multiple nodes based on slot storage. Data is shared among nodes to dynamically adjust data distribution.
  3. Scalability, linear scaling up to 1000 nodes, nodes can be added or removed dynamically.
  4. High availability. The cluster is still available when some nodes are unavailable. Add Slave to make backup data copy
  5. Automatic failover is implemented. Status information is exchanged between nodes through the Gossip protocol. Role promotion from Slave to Master is completed by voting mechanism.

Disadvantages:

  1. Resource isolation is poor, and it is easy to affect each other.
  2. Asynchronous data replication does not ensure strong data consistency

What is a consistent hash algorithm? What is a hash slot?

These two questions are too long and there are two good articles unlocked online

www.cnblogs.com/lpfuture/p/…

Blog.csdn.net/z1573262158…

Redis is based on CAP theory. What is CAP theory?

Refer to my last article.

If someone asks you what CAP theory is, send them this article.

Redis common command?

  • Keys pattern

Check whether an Exists key that starts with bit Exists

  • Set

Set the value of key to a string value.

  • setnx

Set the value of key to a string value. If the key already exists, return 0, nx means not exist. Deleting a key returns 1 the first time. Deleting a key returns 0 the second time

  • Expire

Setting the expiration time in seconds

  • TTL

Check how much time is left

  • Setex

Set the value corresponding to the key to a string value and specify the validity period corresponding to the key value.

  • Mset

Set multiple key values at once. Ok on success means all values are set, and 0 on failure means none is set.

  • Getset

Sets the value of key and returns the old value of key.

  • Mget

Retrieves the value of multiple keys at once, and returns nil if the corresponding key does not exist.

  • Incr

Add to key and return the new value. Incr a value that is not an int returns an error. Incr a key that does not exist. Set the key to 1

  • incrby

Similar to incr, if the specified value is not present, the key is set and the original value is assumed to be 0

  • Decr

Decr if a key does not exist, set the key to -1

  • Decrby

Same as decr, minus the specified value.

  • Append

Appends value to the string value specified by key, returning the length of the new string value.

  • Strlen

Takes the length of the value of the specified key.

  • persist

Cancel expiration time

  • Select

Select database

  • Randomkey

Returns a random key

  • Rename

rename

  • Type

Return data type

Have you ever used Redis distributed lock and how is it implemented?

Use setnx to fight for locks, and use expire to add an expiration time to locks in case they are forgotten to release. What happens if a process crashes unexpectedly or needs to restart maintenance after executing EXPIRE after setnx? The set directive has very complex parameters. It should be possible to combine setnx and EXPIRE into one directive.

Have you ever used Redis for asynchronous queues and how? What are the disadvantages?

The list structure is typically used as a queue, with RPUSH producing messages and LPOP consuming messages. When there are no LPOP messages, sleep for a while and try again. Disadvantages: Production messages can be lost when the consumer goes offline, using professional message queues such as RabbitMQ. Can we produce once and consume many times? Using the PUB/SUB topic subscriber pattern, a 1:N message queue can be implemented.

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

The cache penetrates the general cache system, which caches the query according to the key. If there is no corresponding value, go to the back-end system (such as DB) to find it. Some malicious requests intentionally look for nonexistent keys, and the volume of requests can cause a lot of stress on the backend system. This is called cache penetration. How to avoid it? 1: Cache if the query result is empty, set the cache time to be shorter, or clear the cache after the data corresponding to the key is inserted. 2: Filters non-existent keys. You can put all possible keys into a large Bitmap and filter the query through this Bitmap.

Cache avalanche when a cache server restarts or a large number of caches fail at a particular time, it can put a lot of stress on the backend system when they fail. The system crashes. How to avoid it?

1: Controls the number of threads that can read the database write cache by locking or queuing after the cache is invalid. For example, only one thread is allowed to query data and write to the cache for a key, while the other threads wait. A1 is the original cache and A2 is the copy cache. When A1 fails, access to A2 is available. Set the expiration time of A1 cache to short term and A2 to long term

More content to sort out a brain map, convenient for everyone to remember.Recently, I started a group chat. Learn Java advanced technology dry goods, practice sharing, job promotion, talk about the ideal. Like-minded friends, welcome to join.

All right, good luck with your interview!