This article brings you relevant knowledge about Redis, which mainly introduces some advantages and characteristics of redis. Redis is an open source written in ANSI C language and complies with the BSD protocol. It supports network, can be based on memory, and distributed storage database. Let’s take a look at it. I hope it will be helpful to everyone.
Recommended learning: Redis video tutorial
Remote DIctionary Server (Redis) is a The key-value storage system written by Salvatore Sanfilippo is a cross-platform non-relational database.
Redis is an open source key-value (Key-Value) storage database written in ANSI C language, complying with the BSD protocol, supporting network, memory-based, distributed, and optional persistence, and provides multiple language API.
Redis is often called a data structure server because values can be strings, hashes, lists, sets and sorted sets ) and other types.
1. It is completely based on memory. Most requests are pure memory operations, which are very fast. The data is stored in memory, similar to HashMap. The advantage of HashMap is that the time complexity of search and operation is O(1);
2. The data structure is simple, and the data operation is also simple. The data structure in Redis It is specially designed;
3. It uses a single thread to avoid unnecessary context switching and competition conditions. There is no switching caused by multi-process or multi-threading to consume the CPU, and there is no need to consider various locks. There is no problem of locking and releasing locks, and there is no performance consumption caused by possible deadlocks;
4. Use multi-channel I/O multiplexing model, non-blocking IO;
5. The underlying models used are different, the underlying implementation methods and the application protocols for communication with the client are different. Redis directly builds the VM mechanism by itself, because if the general system calls system functions, it will waste a certain amount of time. Movement and request;
6.Multiple I/O reuse model
The multi-channel I/O multiplexing model uses select, poll, and epoll to monitor the I/O events of multiple streams at the same time. When idle, the current thread will be blocked. When one or more When a stream has an I/O event, it wakes up from the blocking state, so the program polls all streams (epoll only polls those streams that actually emitted events), and only processes the ready streams in sequence. This approach avoids a lot of useless operations.
**Here "multi-channel" refers to multiple network connections, and "reuse" refers to reusing the same thread. **The use of multi-channel I/O multiplexing technology allows a single thread to efficiently handle multiple connection requests (minimizing the time consumption of network IO), and Redis operates data in memory very quickly, which means that in-memory Operation will not become a bottleneck affecting Redis performance. The above points mainly contribute to Redis's high throughput.
We must first understand that the above analyzes are all to create an atmosphere where Redis is fast! The official FAQ states that because Redis is a memory-based operation, the CPU is not the bottleneck of Redis. The bottleneck of Redis is most likely the size of the machine memory or the network bandwidth. Since single-threading is easy to implement and the CPU will not become a bottleneck, it is logical to adopt a single-threaded solution (after all, using multi-threading will cause a lot of trouble!).
redis 127.0.0.1:6379> SET rediskey redis OK redis 127.0.0.1:6379> GET rediskey "redis"
Redis hash is a mapping table of string type fields and values. Hash is particularly suitable for storing objects.
Each hash in Redis can store 232-1 key-value pairs (more than 4 billion)
Redis list is a simple list of strings, sorted in insertion order. You can add an element to the head (left) or tail (right) of the list
A list can contain up to 232 - 1 elements (4294967295, more than 4 billion elements per list).
redis 127.0.0.1:6379> LPUSH rediskey redis (integer) 1 redis 127.0.0.1:6379> LPUSH rediskey mongodb (integer) 2 redis 127.0.0.1:6379> LPUSH rediskey mysql (integer) 3 redis 127.0.0.1:6379> LRANGE rediskey 0 10 1) "mysql" 2) "mongodb" 3) "redis"
Redis’ Set is an unordered collection of String type. Set members are unique, which means that duplicate data cannot appear in the set.
The encoding of the collection object can be intset or hashtable.
Collections in Redis are implemented through hash tables, so the complexity of adding, deleting, and searching is O(1).
The maximum number of members in a collection is 232 - 1 (4294967295, each collection can store more than 4 billion members).
redis 127.0.0.1:6379> SADD rediskey redis (integer) 1 redis 127.0.0.1:6379> SADD rediskey mongodb (integer) 1 redis 127.0.0.1:6379> SADD rediskey mysql (integer) 1 redis 127.0.0.1:6379> SADD rediskey mysql (integer) 0 redis 127.0.0.1:6379> SMEMBERS rediskey 1) "mysql" 2) "mongodb" 3) "redis"
Redis Ordered set, like a set, is also a collection of string type elements, and duplicate members are not allowed.
The difference is that each element is associated with a double type score. Redis uses scores to sort the members of the collection from small to large.
The members of an ordered set are unique, but the scores can be repeated.
Sets are implemented through hash tables, so the complexity of adding, deleting, and searching is O(1). The maximum number of members in a collection is 232 - 1 (4294967295, each collection can store more than 4 billion members).
Redis added the HyperLogLog structure in version 2.8.9.
Redis HyperLogLog is an algorithm used for cardinality statistics. The advantage of HyperLogLog is that when the number or volume of input elements is very, very large, the space required to calculate the cardinality is always fixed and very small. .
In Redis, each HyperLogLog key only costs 12 KB of memory to calculate the cardinality of nearly 2^64 different elements. This is in sharp contrast to a collection that consumes more memory when calculating cardinality. The more elements there are, the more memory is consumed.
However, because HyperLogLog will only calculate the cardinality based on the input elements and will not store the input elements themselves, HyperLogLog cannot return each element of the input like a collection.
For example, if the data set is {1, 3, 5, 7, 5, 7, 8}, then the cardinality set of this data set is {1, 3 , 5 ,7, 8}, the cardinality (non-repeating elements) is 5. Cardinality estimation is to quickly calculate the cardinality within the acceptable error range.
The following example demonstrates the working process of HyperLogLog:
//添加指定元素到 HyperLogLog 中。 redis 127.0.0.1:6379> PFADD rediskey "redis" 1) (integer) 1 redis 127.0.0.1:6379> PFADD rediskey "mongodb" 1) (integer) 1 redis 127.0.0.1:6379> PFADD rediskey "mysql" 1) (integer) 1 //添加指定元素到 HyperLogLog 中。 redis 127.0.0.1:6379> PFCOUNT rediskey (integer) 3
Redis publish and subscribe (pub/sub) is a Message communication mode: sender (pub) sends messages, and subscribers (sub) receive messages.
Redis clients can subscribe to any number of channels.
The following figure shows the relationship between channel channel1 and the three clients that subscribe to this channel - client2, client5 and client1:
The following example demonstrates how publish and subscribe work. Two redis-cli clients need to be opened.
In our example we created a subscription channel named runoobChat:
redis 127.0.0.1:6379> SUBSCRIBE runoobChat Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "runoobChat" 3) (integer) 1
现在,我们先重新开启个 redis 客户端,然后在同一个频道 runoobChat 发布两次消息,订阅者就能接收到消息。
redis 127.0.0.1:6379> PUBLISH runoobChat "Redis PUBLISH test" (integer) 1 redis 127.0.0.1:6379> PUBLISH runoobChat "Learn redis by runoob.com" (integer) 1 # 订阅者的客户端会显示如下消息 1) "message" 2) "runoobChat" 3) "Redis PUBLISH test" 1) "message" 2) "runoobChat" 3) "Learn redis by runoob.com"
gif 演示如下:
runoobChat
频道。Redis 事务可以一次执行多个命令, 并且带有以下三个重要的保证:
一个事务从开始到执行会经历以下三个阶段:
以下是一个事务的例子, 它先以 MULTI 开始一个事务, 然后将多个命令入队到事务中, 最后由 EXEC 命令触发事务, 一并执行事务中的所有命令:
redis 127.0.0.1:6379> MULTI OK redis 127.0.0.1:6379> SET book-name "Mastering C++ in 21 days" QUEUED redis 127.0.0.1:6379> GET book-name QUEUED redis 127.0.0.1:6379> SADD tag "C++" "Programming" "Mastering Series" QUEUED redis 127.0.0.1:6379> SMEMBERS tag QUEUED redis 127.0.0.1:6379> EXEC 1) OK 2) "Mastering C++ in 21 days" 3) (integer) 3 4) 1) "Mastering Series" 2) "C++" 3) "Programming"
单个 Redis 命令的执行是原子性的,但 Redis 没有在事务上增加任何维持原子性的机制,所以 Redis 事务的执行并不是原子性的。
事务可以理解为一个打包的批量执行脚本,但批量指令并非原子化的操作,中间某条指令的失败不会导致前面已做指令的回滚,也不会造成后续的指令不做。
这是官网上的说明 From redis docs on transactions:
It’s important to note that even when a command fails, all the other commands in the queue are processed – Redis will not stop the processing of commands.
比如:
redis 127.0.0.1:7000> multi OK redis 127.0.0.1:7000> set a aaa QUEUED redis 127.0.0.1:7000> set b bbb QUEUED redis 127.0.0.1:7000> set c ccc QUEUED redis 127.0.0.1:7000> exec 1) OK 2) OK 3) OK
如果在 set b bbb 处失败,set a 已成功不会回滚,set c 还会继续执行。
Redis 脚本使用 Lua 解释器来执行脚本。 Redis 2.6 版本通过内嵌支持 Lua 环境。执行脚本的常用命令为 EVAL。
redis 127.0.0.1:6379> EVAL "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1 key2 first second 1) "key1" 2) "key2" 3) "first" 4) "second"
Redis GEO 主要用于存储地理位置信息,并对存储的信息进行操作,该功能在 Redis 3.2 版本新增。
Redis GEO 操作方法有:
redis> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania" (integer) 2 redis> GEODIST Sicily Palermo Catania "166274.1516" redis> GEORADIUS Sicily 15 37 100 km 1) "Catania" redis> GEORADIUS Sicily 15 37 200 km 1) "Palermo" 2) "Catania" redis>
Redis Stream 是 Redis 5.0 版本新增加的数据结构。
Redis Stream 主要用于消息队列(MQ,Message Queue),Redis 本身是有一个 Redis 发布订阅 (pub/sub) 来实现消息队列的功能,但它有个缺点就是消息无法持久化,如果出现网络断开、Redis 宕机等,消息就会被丢弃。
简单来说发布订阅 (pub/sub) 可以分发消息,但无法记录历史消息。
而 Redis Stream 提供了消息的持久化和主备复制功能,可以让任何客户端访问任何时刻的数据,并且能记住每一个客户端的访问位置,还能保证消息不丢失。
Redis Stream 的结构如下所示,它有一个消息链表,将所有加入的消息都串起来,每个消息都有一个唯一的 ID 和对应的内容:
每个 Stream 都有唯一的名称,它就是 Redis 的 key,在我们首次使用 xadd 指令追加消息时自动创建。
上图解析:
Redis is a TCP service based on the client-server model and request/response protocol. This means that normally a request will follow the following steps:
Redis pipeline technology allows the client to continue sending requests to the server when the server does not respond, and eventually reads all services at once end response.
Recommended learning: Redis video tutorial
The above is the detailed content of Let's talk about the advantages and features of Redis. For more information, please follow other related articles on the PHP Chinese website!