什么是 Redis
The open source, in-memory data store userd by millions of developers as a database, cache, streaming engine, and message broker.
上述为 Redis 官网对 Redis 的描述。
Redis 是一个开源的,在内存中通过键值对的方式存储数据的数据库。
与 MySQL 不同的是,Redis 将数据存储在了内存中,因此访问速度非常快。
其还可以作为缓存,与 MySQL 等数据库搭配使用,用于缓存那些数据量访问大的数据,提高访问速度。
还可以作为消息队列,Redis 的初心,就是用来作为消息队列的。
Redis 只有在分布式系统中,才能发挥其最大的作用,如果是传统的单机系统,使用 Redis 反而会使系统的性能下降。
Redis 特性
In-memory data structure
support for strings, hashes, lists, sets, sorted sets, streans, and more.
Redis 与 MySQL 等关系型数据库不同,MySQL 是通过 “表” 的方式组织数据的,而 Redis 则是通过 “键值对” 的方式组织数据的,一般被称为 非关系型数据库。
Redis 的 key 都为 string,value 则是上述数据结构中的一种。
Programmability
Server-size scripting with Lua and server-side stored procedures with Redis Functions.
Redis 提供了 Lua 脚本语言,可以让用户编写脚本,在服务器端执行一些复杂的操作。
Extensibility
A module API for building custom extensions to Redis in C, C++, and Rust.
通过 C,C++ 和 Rust 语言,可以扩展 Redis 的功能。
可扩展性也是 Redis 火爆的原因之一。
Persistence
Keeps the dataset in memory for fast access but can also persist all writes to permanent storage to survive reboots and system failures.
内存是易失性的,Redis 会把数据再备份一份存储到硬盘上,在 Redis 重启后,就会在重启时从硬盘上加载备份数据。
Clustering
Horizontal scalability with hash-based sharding, scaling to millions of nodes with automatic re-partitioning when growing the cluster.
Redis 是支持集群的,Redis 的集群是基于 hash 的,当集群中的节点增加时,Redis 会自动进行重新分区。
这个水平扩展,类似于 “分库分表”。
High availability
Replication with automatic failover for both standalone and clustered deployments.
Redis 也是支持 “主从” 结构的,当主节点挂掉时,从节点会自动顶替主节点,继续提供服务。
使用案例
Real-time data store
Redis’ versatile in-memory data structures enable building data infrastructure for real-time applications that require low latency and high-throughput.
Redis 作为数据库使用是当今最为流行的使用场景。
对于一些需要数据低延迟,高吞吐量的业务,Redis 是最佳选择。
Caching & session storage
Redis’ speed makes it ideal for caching database queries, complex computations, API calls, and session state.
与 MySQL 等数据库搭配使用,用于缓存那些数据量访问大的数据,提高访问速度。
Redis 还可以用来存储 session 信息,用于分布式系统中。
Streaming & messaging
The stream data type enables high-rate data ingestion, messaging, event sourcing, and notifications.
Redis 也可以作为消息队列,引入消息队列,有解耦合、削峰填谷的作用。
Redis 的优缺点
优点
其最大的优点就是 “快”。
Redis 的数据是存放在内存中的,就比访问硬盘的数据库,要快得多。
Redis 的核心功能都是比较简单的逻辑,核心功能都是比较简单的操作内存的数据结构
从网络角度来说,Redis 使用了 IO 多路复用技术,可以处理大量的并发请求。
Redis 使用的是单线程模型,避免了上下文切换,减少了线程切换的开销。
缺点
其最大缺点就是,不能存储大量数据。
Redis 的数据是存放在内存中的,因此如果数据量过大,会导致内存不足,从而导致 Redis 崩溃。