Home > Database > Redis > body text

Let's talk about the advantages and features of Redis

WBOY
Release: 2022-05-16 18:04:09
forward
4487 people have browsed it

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

What is redis

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.

Features of Redis:

  • In-memory database is fast and supports data persistence. It can save the data in the memory to the disk and load it again when restarting. use.
  • Redis not only supports simple key-value type data, but also provides storage of data structures such as list, set, zset, and hash.
  • Redis supports data backup, that is, data backup in master-slave mode.
  • Support transactions

Advantages of Redis:

  • Extremely high performance – Redis can read at a speed of 110,000 times/s and write at a speed of 81,000 times/s.
  • Rich data types – Redis supports Strings, Lists, Hashes, Sets and Ordered Sets data type operations for binary cases.
  • Atomic - All operations of Redis are atomic, and Redis also supports atomic execution after merging several operations. (Transaction)
  • Rich features – Redis also supports publish/subscribe, notifications, key expiration and other features.

What is the difference between Redis and other key-value stores?

  • Redis has more complex data structures and provides atomic operations on them. This is an evolutionary path different from other databases. Redis's data types are based on basic data structures and are transparent to programmers, without the need for additional abstractions.
  • Redis runs in memory but can be persisted to disk, so memory needs to be weighed when performing high-speed reading and writing of different data sets, because the amount of data cannot be larger than the hardware memory. Another advantage of in-memory databases is that compared to the same complex data structures on disk, operating in memory is very simple, so Redis can do a lot of things with strong internal complexity. Also, in terms of disk format they are compact append-generated since they do not require random access.

What are the differences between Memcache and Redis

  1. Storage method Memecache stores all data in the memory. It will hang up after a power outage. The data cannot exceed the memory size. Part of Redis is stored on the hard disk, and redis can persist its data
  2. Data support type memcached All values ​​are simple strings. As its replacement, redis supports richer data types and provides list , the storage of data structures such as set, zset, hash
  3. The underlying models used are different, and the underlying implementation methods and application protocols for communication with the client are different. Redis directly built its own VM mechanism, because if the general system calls system functions, it will waste a certain amount of time to move and request.
  4. value The value size is different: Redis can reach a maximum of 512M; memcache is only 1mb.
  5. The speed of redis is much faster than memcached
  6. Redis supports data backup, that is, data backup in master-slave mode.

Why is Redis so fast?

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.

So why is Redis single-threaded?

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 data types and commands

1. String(String)

redis 127.0.0.1:6379> SET rediskey redis
OK
redis 127.0.0.1:6379> GET rediskey
"redis"
Copy after login

2. Hash(Hash)

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)

3. List(List)

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"
Copy after login

4. Set

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"
Copy after login

5. Sorted set

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).

6. HyperLogLog

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.

What is the cardinality?

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.

Example

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
Copy after login

7. Publish and subscribe

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:

Example

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-cli 客户端

redis 127.0.0.1:6379> SUBSCRIBE runoobChat

Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "runoobChat"
3) (integer) 1
Copy after login

现在,我们先重新开启个 redis 客户端,然后在同一个频道 runoobChat 发布两次消息,订阅者就能接收到消息。

第二个 redis-cli 客户端

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"
Copy after login

gif 演示如下:

  • 开启本地 Redis 服务,开启两个 redis-cli 客户端。
  • 第一个 redis-cli 客户端输入 SUBSCRIBE runoobChat,意思是订阅 runoobChat 频道。
  • 第二个 redis-cli 客户端输入 PUBLISH runoobChat “Redis PUBLISH test” 往 runoobChat 频道发送消息,这个时候在第一个 redis-cli 客户端就会看到由第二个 redis-cli 客户端发送的测试消息。

8. 事务

Redis 事务可以一次执行多个命令, 并且带有以下三个重要的保证:

  • 批量操作在发送 EXEC 命令前被放入队列缓存。
  • 收到 EXEC 命令后进入事务执行,事务中任意命令执行失败,其余的命令依然被执行。
  • 在事务执行过程,其他客户端提交的命令请求不会插入到事务执行命令序列中。

一个事务从开始到执行会经历以下三个阶段:

  • 开始事务。
  • 命令入队。
  • 执行事务。

实例

以下是一个事务的例子, 它先以 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"
Copy after login

单个 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
Copy after login

如果在 set b bbb 处失败,set a 已成功不会回滚,set c 还会继续执行。

9. 脚本

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"
Copy after login

10 GEO

Redis GEO 主要用于存储地理位置信息,并对存储的信息进行操作,该功能在 Redis 3.2 版本新增。

Redis GEO 操作方法有:

  • geoadd:添加地理位置的坐标。
  • geopos:获取地理位置的坐标。
  • geodist:计算两个位置之间的距离。
  • georadius:根据用户给定的经纬度坐标来获取指定范围内的地理位置集合。
  • georadiusbymember:根据储存在位置集合里面的某个地点获取指定范围内的地理位置集合。
  • geohash:返回一个或多个位置对象的 geohash 值。
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>
Copy after login

11 Redis Stream

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 指令追加消息时自动创建。

上图解析:

  • Consumer Group: Consumer group, created using the XGROUP CREATE command. A consumer group has multiple consumers (Consumers).
  • last_delivered_id: Cursor, each consumer group will have a cursor last_delivered_id. Any consumer reading the message will move the cursor last_delivered_id forward.
  • pending_ids: The state variable of the consumer, which is used to maintain the unconfirmed id of the consumer. pending_ids records messages that have been read by the client but have not yet received an ack (Acknowledge character).

Redis pipeline technology

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:

  • The client sends a query request to the server and listens for the Socket return, usually in blocking mode, waiting for the server to respond.
  • The server processes the command and returns the result to the client.

Redis pipeline technology

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!