1. What data types does Redis support?
String _
Hash _
List (list)
Set _
zset (sorted set: ordered collection)
1. String (string)
Format: set key value
The string type is binary safe, meaning redis
The string can contain any data, such as jpg
slice or serialized object
The string type is the most basic data type of Redis,
A key can store up to 512 MB
2. Hash
Format: hmset name key1 value1 key2 value2
Redis hash is a set of key-value (key=>value) pairs
combine
Redis hash is a field of type string and
Value mapping table, hash is especially suitable for storage
object
3. List (list)
Redis lists are simply lists of strings,
In order to sort, you can add an element to the list
head (left) or tail (right)
Format: lpush name value
Add a string element at the head of the list corresponding to the key
Format: rpush name value
Add a string element at the end of the list corresponding to the key
Format: lrem name index
key corresponds to delete count and value in the list
same element
Format: llen name
Returns the length of the list corresponding to the key
4. Set (collection)
Format: sadd name value
Redis's Set is an unordered collection of string types
Sets are implemented with hash tables , so adding,
The complexity of deletion and search is O(1)
5. ZSet (sorted set: ordered collection)
Format: zadd name score value
Redis zset is also a string type like set
A collection of elements that do not allow duplicate members
The difference is that each element will be associated with a double
The type of score, redis is set for the set through the score
The members in the combination are sorted from small to large
The members of zset are unique, but the score (score) can be
to repeat
2. What is Redis persistence ? What kinds of persistence methods does Redis have? What are the pros and cons?
Persistence is to write the data in the memory to the disk.
Prevent service downtime from memory data loss
Redis provides two persistence methods:
RDB (default)
AOF
1. RDB:
rdb is the abbreviation of Redis DataBase
Function core function rdbSave (generate RDB file)
and rdbLoad (load memory from file) two functions
2. AOF:
Aof is the abbreviation of Append-only file
Whenever a server (scheduled) task or function is executed
The flushAppendOnlyFile function will be called,
This function performs the following two tasks
aof write save:
WRITE : According to the conditions, the cache in aof_buf
Write to AOF file
SAVE : Depending on the condition, call fsync or fdatasync
Function to save AOF file to disk
Storage structure:
The content is a command in redis communication protocol (RESP) format
text storage
Compare:
① The update frequency of aof file is higher than that of rdb, so it should be used first
aof restore data
② aof is safer and bigger than rdb
③ rdb performance is better than aof
④ If both are equipped with priority loading AOF
RESP is used by redis client and server before
a communication protocol ;
Features of RESP: simple implementation, fast parsing, good readability
For Simple Strings the first byte of the reply is "+" 回复
For Errors the first byte of the reply is "-" 错误
For Integers the first byte of the reply is ":" 整数
For Bulk Strings the first byte of the reply is "$" 字符串
For Arrays the first byte of the reply is "*" 数组
3. What architectural patterns does Redis have? talk about their characteristics
② Master-slave mode
③ Sentry mode
④ cluster mode
1. Standalone mode
Features:
Simple
question:
① Limited memory capacity
② limited processing capacity
③ Cannot be highly available
2. Master-slave mode
The replication function of Redis allows the user root
According to a Redis server to create any number of the server
replica of the server, where the replicated server is the master
Server (master) , and created by replication
The server replica is the slave server (slave)
As long as the network connection between the master and slave servers is normal, the master
Both slave servers will have the same data, the master server
The device will always update the data that happened to itself
Synchronize to the slave server, so that the master-slave service is always guaranteed
The data of the device is the same
Features:
① master/slave role
② Master/slave data is the same
③ Reduce the master read pressure and transfer it to the slave library
question:
① High availability cannot be guaranteed
② Did not solve the pressure of master writing
3. Sentry Mode
Redis sentinel is a distributed system monitoring
Redis master-slave server, and when the master server goes offline
Automatic failover
Three of these properties:
Monitoring : Sentinel will constantly check
Check if your master and slave are working
often
Notification : When a monitored
When there is a problem with the Redis server, Sentinel
It can be sent to the administrator or other applications through the API
Program sends notification
Automatic failover :
When a primary server fails to function properly,
Sentinel will start an automatic failover operation
Features:
① Ensure high availability
② Monitor each node
③ Automatic fault migration
shortcoming:
① Master-slave mode, switching takes time to lose data
② Did not solve the pressure of master writing
4. Cluster mode
(1) Cluster (proxy type)
Twemproxy is a Twitter open source redis
and memcache fast/lightweight proxy server;
Twemproxy is a fast, single-threaded proxy that
Support Memcached ASCII protocol and redis protocol
Features:
① Multiple hash algorithms: MD5, CRC16, CRC32,
CRC32a、hsieh、murmur、Jenkins
② Support automatic deletion of failed nodes
③ Backend Sharding sharding logic is transparent to business, business
The reading and writing method of the party is consistent with the operation of a single Redis
shortcoming:
① A new proxy has been added, and its high availability needs to be maintained
② The failover logic needs to be implemented by itself, which cannot be supported by itself
The scalability of the automatic transfer of the support failure is poor, and the expansion and contraction are carried out
both require manual intervention
(2) Cluster (direct connection type):
Redis-cluster clusters are supported from versions after redis 3.0,
Redis-Cluster adopts a centerless structure, and each node maintains
Store data and the entire cluster state, each node and other
All nodes are connected
Features:
① Decentralized architecture (there is no node that affects performance bottlenecks),
Less proxy layer
② Data is distributed among multiple nodes according to slot storage, and between nodes
Data sharing, which can dynamically adjust data distribution
③ Scalability, can be linearly expanded to 1000 nodes,
Points can be added or removed dynamically.
④ High availability, when some nodes are unavailable, the cluster is still available
By adding Slave as a backup data copy to achieve self-failure
Dynamic failover, exchange between nodes through gossip protocol
Status information, use the voting mechanism to complete Slave to Master
The role of
shortcoming:
Poor isolation of resources, prone to mutual influence
The data is replicated asynchronously, which does not guarantee the strong consistency of the data
4. Have you ever used Redis distributed locks? How is it implemented?
First use setnx to compete for the lock, and then use expire
Add an expiration time to the lock to prevent the lock from forgetting to release
1. If the process is unexpected before executing expire after setnx
Crash or restart maintenance, what will happen?
The set command has very complex parameters, this should be possible
At the same time, setnx and expire are combined into one instruction to use!
5. Have you ever used Redis as an asynchronous queue? How did you use it? What are the disadvantages?
Generally use the list structure as a queue, rpush produces messages,
lpop consumption message
When there is no news from lpop, it is necessary to sleep for a while
try again
In the case of consumers going offline, the produced messages will be lost,
You have to use a professional message queue such as rabbitmq, etc.
Can it be produced once and consumed multiple times?
Using the pub/sub topic subscriber pattern, you can achieve
1:N message queue
6. What is cache penetration? How to avoid it? What is cache avalanche? How to avoid it?
1. Cache penetration
The general cache system is to cache and query according to the key.
Query, if there is no corresponding value, it should go to
Backend system lookup (such as DB)
Some malicious requests will intentionally query keys that do not exist,
A large amount of requests will cause a great impact on the back-end system
Pressure, this is called cache penetration
How to avoid it?
① Even if the query result is empty, cache
Set the storage time to be shorter, or the key corresponding to
Clean up the cache after the data is inserted
② To filter the keys that must not exist, you can put
All possible keys are put into a large
In Bitmap , filter through this bitmap when querying
2. Cache Avalanche
When the cache server restarts or a large number of caches are concentrated in a certain
A period of time expires , so that when it expires, it will
Put a lot of pressure on the backend system, causing the system to crash
How to avoid it?
① After the cache is invalidated, control the cache by locking or queuing
Limit the number of threads to read and write to the database cache
For example, only one thread is allowed to query a certain key
Data and write cache, other threads wait
② Make the secondary cache , A1 is the original cache, A2 is the copy
Bay cache, when A1 fails, you can access A2, A1
The cache expiration time is set to short and A2 is set to long
Expect
③ For different keys, set different expiration times , so that
The time point of cache invalidation should be as uniform as possible
Seven, Redis common commands
1. Management commands
# dbsize 返回当前数据库 key 的数量。
# info 返回当前 redis 服务器状态和一些统计信息。
# monitor 实时监听并返回redis服务器接收到的所有请求信息。
# shutdown 把数据同步保存到磁盘上,并关闭redis服务。
# config get parameter 获取一个 redis 配置参数信息。(个别参数可能无法获取)
# config set parameter value 设置一个 redis 配置参数信息。(个别参数可能无法获取)
# config resetstat 重置 info 命令的统计信息。(重置包括:keyspace 命中数、
# keyspace 错误数、 处理命令数,接收连接数、过期 key 数)
# debug object key 获取一个 key 的调试信息。
# debug segfault 制造一次服务器当机。
# flushdb 删除当前数据库中所有 key,此方法不会失败。小心慎用
# flushall 删除全部数据库中所有 key,此方法不会失败。小心慎用
2. Tool commands
#redis-server:Redis 服务器的 daemon 启动程序
#redis-cli:Redis 命令行操作工具。当然,你也可以用 telnet 根据其纯文本协议来操作
#redis-benchmark:Redis 性能测试工具,测试 Redis 在你的系统及你的配置下的读写性能
$redis-benchmark -n 100000 –c 50
#模拟同时由 50 个客户端发送 100000 个 SETs/GETs 查询
#redis-check-aof:更新日志检查
#redis-check-dump:本地数据库检查