Internet companies interview frequently asked Redis topics

Source: Internet
Author: User
Tags failover redis server

Redis is a very fire non-relational database, how much fire? As long as an internet company will use it. Redis related questions can be said to be the interview must ask, below I from the personal experience as an interviewer, summed up a few must master the knowledge points. (More knowledge, I put together a mind map, back to Redis, sent to you) Introduction: Redis is an open source using ANSI C language, comply with BSD protocol, support network, can be based on memory and persistent log-type, Key-value database, and provide multiple languages The non-relational database of the API. Traditional databases follow ACID rules. The acronym for NOSQL (not just SQL) is a general designation of a database management system that differs from a traditional relational database, and generally follows the CAP theorem for distributed distribution.

Github Source: Https://github.com/antirez/redis

Redis Official website: https://redis.io/

01

What type of data does Redis support?

String strings:

Format: Set key value

The string type is binary safe. This means that a Redis string can contain any data. For example, JPG images or serialized objects.

The string type is the most basic data type of Redis, and a key can store up to 512MB.

Hash (hashed)

Format: Hmset name Key1 value1 key2 value2

A Redis hash is a key-value (Key=>value) pair collection.

Redis Hash is a string-type field and value mapping table, and hash is particularly useful for storing objects.

List (lists)

The Redis list is a simple list of strings, sorted by insertion order. You can add an element to the head of the list (to the left) or to the tail (to the right)

Format: Lpush Name value

Adds a string element to the head of the list in key

Format: Rpush Name value

Add a string element at the end of the key corresponding list

Format: Lrem name index

Key corresponds to the list to remove count and value elements of the same

Format: Llen name

Returns the length of the key corresponding to the list

Set (SET)

Format: Sadd Name value

Redis's set is an unordered collection of type string.

The collection is implemented by a hash table, so the complexity of adding, deleting, and finding is O (1).

Zset (sorted set: Ordered set)

Format: Zadd Name score Value

Redis Zset and set are also collections of string-type elements and do not allow duplicate members.

The difference is that each element is associated with a double-type fraction. Redis is a small-to-large ordering of the members in a collection by fractions.

Zset members are unique, but fractions (score) can be duplicated.

02

What is Redis persistence? What kinds of persistence do redis have? What are the pros and cons?

Persistence is the memory data written to disk, to prevent service downtime memory loss.

Redis provides two ways to persist: RDB (default) and AOF

Rdb:

RDB is a redis database abbreviation

function Core function rdbsave (generate RDB file) and rdbload (load memory from file) two functions

AOF:

AOF is the append-only file abbreviation

The Flushappendonlyfile function is called whenever a server (timed) task or function is executed, and the function performs the following two jobs

AoF Write Save:

Write: Writes the cache in Aof_buf to the AoF file, depending on the condition

Save: Depending on the condition, call the Fsync or Fdatasync function to save the AOF file to disk.

Storage structure:

The content is a command text store in the Redis Communication Protocol (RESP) format.

Comparison:

1. aof files are more frequent than RDB, and use AOF to restore data preferentially.

2. AoF is safer and larger than an RDB

3, RDB performance than aof good

4, if two are equipped with a priority load AOF

03

Just above you mentioned Redis Protocol (RESP), can explain what is RESP? What are the characteristics? (You can see a lot of interviews are actually serial guns, the interviewer is actually waiting for you to answer this point, if you answered the comments on you added another point)

RESP is a communication protocol used before the Redis client and server;

RESP Features: Simple, fast analysis, 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 ":" Integer

For Bulk Strings The first byte of the reply is "$" string

For Arrays the first byte of the reply is "*" array

04

What are the schema patterns for Redis? Talk about the characteristics of each

Stand-alone version

Features: Simple

Problem:

1, memory capacity is limited 2, processing capacity is limited 3, can not be highly available.

Master-slave replication

The Redis Replication (replication) feature allows the user to create as many replicas of the server as a Redis server, where the server being replicated is the primary server (master), and the server replica created by replication is the slave server (slave). As long as the network connection between the master and slave servers is normal, the master and slave servers will have the same data, the primary server will always be on their own data updates synchronized to the slave server, thus ensuring that the master-slave server data is the same.

Characteristics:

1. Master/slave role

2, Master/slave data is the same

3, reduce the master reading pressure in the transfer from the library

Problem:

No guarantee of high availability

does not solve the pressure of master writing

Sentinel

Redis Sentinel is a distributed system that monitors Redis master-slave servers and automatically fails over when the primary server is offline. Three of these features:

Monitoring (Monitoring): Sentinel will constantly check whether your primary server and slave server are functioning properly.

Reminder (Notification): When a problem occurs with a Redis server being monitored, Sentinel can send notifications to administrators or other applications through the API.

Automatic failover (Automatic failover): Sentinel starts an automatic failover operation when a primary server is not working properly.

Characteristics:

1. Guaranteed High Availability

2. Monitor each node

3. Automatic fault migration

Cons: Master-slave mode, switching takes time to lose data

does not solve the pressure of master writing

Cluster (proxy type):

Twemproxy is a Twitter open source, a redis and memcache fast/lightweight proxy server; Twemproxy is a fast single-threaded agent that supports Memcached ASCII protocol and Redis protocol.

Features: 1, a variety of hash algorithms: MD5, CRC16, CRC32, crc32a, Hsieh, Murmur, Jenkins

2, support failed node automatic deletion

3, back-end sharding Shard logic to the business transparent, business party read and write mode and operation of a single Redis consistent

Cons: A new proxy is added and needs to be maintained for its high availability.

Failover logic needs to be implemented by itself, it can not support the failure of automatic transfer scalability poor, the expansion of the capacity of the need for manual intervention

Cluster (direct-attached):

After Redis 3.0, the Redis-cluster cluster is supported, the Redis-cluster is in a non-central structure, each node holds the data and the entire cluster state, and each node is connected to all other nodes.

Characteristics:

1, no central architecture (there is no node which affects performance bottlenecks), less proxy layer.

2, the data in accordance with the slot storage distribution in multiple nodes, data sharing between nodes, can dynamically adjust the data distribution.

3, scalability, can be linearly extended to 1000 nodes, the node can be dynamically added or deleted.

4, high availability, some nodes are unavailable, the cluster is still available. Make a copy of backup data by adding Slave

5, realizes the fault automatic failover, the node exchanges the state information through the gossip protocol, uses the voting mechanism to complete slave to the Master the role promotion.

Disadvantages:

1, the resource isolation is poor, prone to mutual influence situation.

2, data through asynchronous replication, does not guarantee strong consistency of data

05

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

These two questions are too long online to find a good two unlocked articles

Https://www.cnblogs.com/lpfuture/p/5796398.html

79121213

06

Redis is based on the CAP theory, what is cap theory?

You can refer to an article.

If someone asks you what the CAP theory is, send him the article.

07

Redis common commands?

Keys pattern

* Indicates the area with all

Starting with a bit

See if exists key exists

Set

Sets the value of the key corresponding to string type.

Setnx

Sets the value of the key corresponding to string type. If key already exists, returning 0,nx is the meaning of not exist.

Delete a key

First return 1 deleted the second return 0

Expire Setting the expiration time (in seconds)

TTL to see how much time is left

Returns a negative key fails, key does not exist

Setex

Set the value of the key to a string type of value and specify the validity period for this key value.

Mset

Setting the value of multiple keys at once, successfully returning OK means that all values are set, and a failure return of 0 means that no value is set.

Getset

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

Mget

Gets the value of more than one key at a time, and returns nil if the corresponding key does not exist.

Incr

Make a Gaga operation on the value of key and return the new value. Note INCR A value that is not an int returns an error incr a nonexistent key, setting key to 1

Incrby

Similar to INCR, plus the specified value, key does not exist when the key is set, and the original value is considered to be 0

Decr

The value of the key is a decrement operation, decr a key does not exist, then set key to 1

Decrby

With DECR, minus the specified value.

Append

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

Strlen

Takes the length of the value of the specified key.

Persist xxx (Cancel expiration)

Select Database (0-15 libraries)

Select 0//Choose Database

Move age 1//The age to 1 libraries

Randomkey randomly returns a key

Rename renaming

Type return data type

08

Have you ever used a Redis distributed lock, and how does it work?

First take SETNX to grab the lock, after the grab, then use expire to lock plus an expiration time to prevent the lock forgot to release.

What happens if the process unexpectedly crash or restarts maintenance before expire is executed after setnx?

The set directive has very complex parameters, which should be used to synthesize setnx and expire as an instruction!

09

Do you use Redis as an asynchronous queue? What are the drawbacks?

Generally use the list structure as a queue, Rpush production messages, Lpop consumer messages. When Lpop has no message, try again with a proper sleep.

Disadvantages:

In the case of the consumer offline, the production of the message will be lost, the use of professional Message Queuing such as RABBITMQ.

Is it possible to produce a single consumption multiple times?

With the Pub/sub theme subscriber pattern, you can implement 1:N Message Queuing.

10

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

Cache penetration

The general cache system is to follow the key to cache the query, if there is no corresponding value, it should go to the backend system lookup (such as DB). Some malicious requests will deliberately query the nonexistent key, the volume of the request is very large, it will cause great pressure on the back-end system. This is called cache penetration.

How to avoid it?

1: The case of NULL query results is also cached, the cache time is set a little bit shorter, or the key corresponding to the data insert after the cache cleanup.

2: Filter The key that does not exist. All possible keys can be placed in a large bitmap, which is filtered by the bitmap when queried.

Cache avalanche

When a cache server restarts or a large number of caches fail at a certain time period, this can put a lot of pressure on the backend system when it fails. Cause the system to crash.

How to avoid it?

1: After the cache fails, the number of threads that read the database write cache is controlled by a lock or queue. For example, a key allows only one thread to query the data and write the cache, and other threads wait.

2: Do two-level cache, A1 for the original cache, A2 for the copy cache, A1 failure, can access A2,A1 cache expiration time set to short-term, A2 set to long-term

3: Different keys, set different expiration time, so that the cache fails to the point of time as evenly as possible.

Internet company interviews frequently asked Redis topics

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.