🧩 Redis Architecture & Setup

🧩 Redis 架构与设置

💡 Introduction to Redis

💡 Redis 简介

  • Redis is a NoSQL key-value database, functioning as an in-memory data store.
  • Redis 是一个 NoSQL 键值数据库,作为一个内存数据存储。
  • It allows fast access to various data structures (strings, lists, sets, etc.) using unique keys.
  • 它允许使用唯一键快速访问各种数据结构(字符串、列表、集合等)。

Key-Value Store: A method of storing data where a key is associated with a value, retrievable only through the exact key.

键值存储:一种数据存储方法,其中一个键与一个值相关联,只能通过确切的键来检索。


🏗️ Redis Architecture

🏗️ Redis 架构

  • Main Components: Client and Server
  • 主要组件:客户端和服务器
    • Can be on the same machine or different machines.
    • 可以在同一台机器上,也可以在不同的机器上。
  • Data Persistence Options:
  • 数据持久化选项
    • RDB (Redis Database): Point-in-time snapshots.
    • RDB (Redis 数据库):时间点快照。
    • AOF (Append Only File): Logs every write action.
    • AOF (仅追加文件):记录每个写操作。

🔑 Types of Redis Architecture

🔑 Redis 架构类型

  1. Redis Standalone
  2. Redis 单机版
    • Single-node architecture.
    • 单节点架构。
    • Pros: Simple deployment and configuration.
    • 优点:部署和配置简单。
    • Cons: Limited data reliability; performance impacted by single-threaded nature.
    • 缺点:数据可靠性有限;性能受单线程特性影响。
  3. Redis Sentinel
  4. Redis 哨兵模式
    • Master-slave architecture for high availability.
    • 主从架构,用于实现高可用性。
    • Features:
    • 特性
      • Monitoring: Checks master and slave instances.
      • 监控:检查主实例和从实例。
      • Notification: Alerts on instance failures.
      • 通知:在实例失败时发出警报。
      • Automatic Failover: Promotes a slave to master upon master failure.
      • 自动故障转移:在主实例失败时将一个从实例提升为主实例。
    • Quorum Agreement: Ensures multiple sentinel processes agree on failures.
    • 法定数量协议:确保多个哨兵进程对故障达成一致。
  5. Redis Cluster
  6. Redis 集群
    • Distributes data across multiple nodes (horizontal scaling).
    • 将数据分布在多个节点上(水平扩展)。
    • Uses HashSlots (16384 slots) for data distribution.
    • 使用 哈希槽(16384个槽)进行数据分布。
    • Pros: Dynamic data distribution and scalable up to 1000 nodes.
    • 优点:动态数据分布,可扩展至1000个节点。
    • Cons: High maintenance costs; potential for lost writes.
    • 缺点:维护成本高;可能存在写操作丢失的风险。

🛠️ Installing Redis on Windows

🛠️ 在 Windows 上安装 Redis

  1. Installation Methods:
  2. 安装方法
    • Installer: Redis-x64-5.0.14.1.msi
    • 安装程序Redis-x64-5.0.14.1.msi
    • ZIP File: Redis-x64-5.0.14.1.zip
    • ZIP 文件Redis-x64-5.0.14.1.zip
  3. Configuring Environment Variables:
  4. 配置环境变量
    • Set PATH to C:\Program Files\Redis;.
    • 设置 PATH 为 C:\Program Files\Redis;
    • Validate installation by running redis-server in the command line.
    • 在命令行中运行 redis-server 来验证安装。
  5. Connecting to Redis:
  6. 连接到 Redis
    • Use command redis-cli to enter interactive mode and execute Redis commands.
    • 使用命令 redis-cli 进入交互模式并执行 Redis 命令。

📊 Key Features of Redis

📊 Redis 的主要特性

  • Binary Safe Keys: Any binary sequence can be used as a key.
  • 二进制安全键:任何二进制序列都可以用作键。
  • Data Structures Supported:
  • 支持的数据结构
    • Strings, Hashes, Lists, Sets, Sorted Sets, Bitmaps, HyperLogLogs, Geospatial indexes.
    • 字符串、哈希、列表、集合、有序集合、位图、HyperLogLogs、地理空间索引。

TTL (Time-To-Live): Keys can expire after a certain period, managed by LRU (Least Recently Used) eviction strategy if the cache is full.

TTL (生存时间):键可以在一定时间后过期,如果缓存已满,则通过 LRU (最近最少使用) 淘汰策略进行管理。


This guide outlines the foundational concepts of Redis architecture, installation, and key features, providing essential information for understanding and using Redis effectively.

本指南概述了 Redis 架构、安装和关键功能的基础概念,为有效理解和使用 Redis 提供了必要信息。

🔗 Redis Connection and Commands

🔗 Redis 连接与命令

Connecting to Redis

连接到 Redis

  • Local Connection:
  • 本地连接
    • Use redis-cli to connect to a local Redis instance (127.0.0.1:6379).
    • 使用 redis-cli 连接到本地 Redis 实例 (127.0.0.1:6379)。
  • Remote Connection:
  • 远程连接
    • Use redis-cli -h host -p port_number -a password to connect remotely.
    • 使用 redis-cli -h 主机 -p 端口号 -a 密码 进行远程连接。
  • Authentication:
  • 认证
    • Use auth password after connecting if required.
    • 如果需要,在连接后使用 auth 密码 进行认证。

Testing Connections

测试连接

  • Ping Command:
  • Ping 命令
    • ping checks the connection; returns PONG if successful.
    • ping 检查连接;如果成功,返回 PONG
    • ping "hello Redis!" returns the string if successful.
    • ping "hello Redis!" 如果成功,返回该字符串。

🚀 Executing Redis Commands

🚀 执行 Redis 命令

Basic Commands

基本命令

  1. SET Command:
  2. SET 命令
    • Syntax: SET key value
    • 语法:SET key value
    • Example: SET name Peter
    • 示例:SET name Peter
  3. GET Command:
  4. GET 命令
    • Syntax: GET key
    • 语法:GET key
    • Example: GET name returns “Peter”.
    • 示例:GET name 返回 “Peter”。
  5. Disconnecting:
  6. 断开连接
    • Use quit or exit to disconnect from Redis.
    • 使用 quitexit 从 Redis 断开。

⚙️ Redis Configuration

⚙️ Redis 配置

Configuration File

配置文件

  • Located at redis.conf.
  • 位于 redis.conf
  • Use CONFIG GET CONFIG_SETTING_NAME to retrieve settings.
  • 使用 CONFIG GET CONFIG_SETTING_NAME 来检索设置。

Updating Configuration

更新配置

  • Retrieve All Settings: CONFIG GET *
  • 检索所有设置CONFIG GET *
  • Set New Configuration: CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE
  • 设置新配置CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE
    • Example: CONFIG SET loglevel "verbose"
    • 示例:CONFIG SET loglevel "verbose"

📊 Redis Data Structures

📊 Redis 数据结构

Overview of Data Structures

数据结构概览

Structure Type Description Commands
结构类型 描述 命令
STRING Sequence of bytes (max 512 MB) SET, GET
字符串 字节序列 (最大 512 MB) SET, GET
LIST Linked list of strings LPUSH, LPOP, LRANGE
列表 字符串的链表 LPUSH, LPOP, LRANGE
SET Unordered collection of unique strings SADD, SREM, SMEMBERS
集合 唯一字符串的无序集合 SADD, SREM, SMEMBERS
HASH Collection of key-value pairs HSET, HGET, HGETALL
哈希 键值对的集合 HSET, HGET, HGETALL
ZSET Ordered mapping of strings to floating-point scores ZADD, ZRANGE
有序集合 字符串到浮点分数的有序映射 ZADD, ZRANGE

Examples of Data Structures

数据结构示例

  • STRING Example:

  • 字符串示例

    1
    2
    SET name "NIIT"
    GET name # Returns "NIIT"
    1
    2
    SET name "NIIT"
    GET name # 返回 "NIIT"
  • HASH Example:

  • 哈希示例

    1
    2
    HMSET user:1 username niit password niit1 points 200
    HGETALL user:1
    1
    2
    HMSET user:1 username niit password niit1 points 200
    HGETALL user:1
  • LIST Example:

  • 列表示例

    1
    2
    LPUSH coursel redis
    LRANGE coursel 0 10 # Returns elements in the list
    1
    2
    LPUSH coursel redis
    LRANGE coursel 0 10 # 返回列表中的元素
  • SET Example:

  • 集合示例

    1
    2
    SADD myset "element1"
    SMEMBERS myset # Returns all elements in the set
    1
    2
    SADD myset "element1"
    SMEMBERS myset # 返回集合中的所有元素

🗝️ Redis Data Structures and Commands

🗝️ Redis 数据结构与命令

1. Sets in Redis

1. Redis 中的集合

  • Sets: A collection of unique strings.

  • 集合:唯一字符串的集合。

  • Example:

  • 示例:

    • Adding elements:

    • 添加元素:

      1
      127.0.0.1:6379> sadd coursel redis
    • Duplicate elements are not added:

    • 重复的元素不会被添加:

      1
      127.0.0.1:6379> sadd coursel rabitmq

2. Sorted Sets

2. 有序集合

  • Sorted Sets: Each element is associated with a score, used for ordering.

  • 有序集合:每个元素都与一个分数相关联,用于排序。

  • Members are unique, but scores can repeat.

  • 成员是唯一的,但分数可以重复。

  • Example:

  • 示例:

    1
    127.0.0.1:6379> zadd niit_course1 0 redis

3. Redis Data Keys

3. Redis 数据键

  • Keys: Identifiers for data structures.
  • :数据结构的标识符。
  • Properties:
  • 属性
    • Naming conventions: Use strings with letters, numbers, and special characters.
    • 命名约定:使用包含字母、数字和特殊字符的字符串。
    • Case sensitivity: user:1 and User:1 are different keys.
    • 大小写敏感:user:1User:1 是不同的键。
    • Expiry: Keys can have an expiration time, useful for caching.
    • 过期:键可以有过期时间,这对于缓存很有用。

Key Space: The set of all keys in Redis.

键空间:Redis 中所有键的集合。

4. Key Commands

4. 键命令

Command Description Syntax Example Return Value
命令 描述 语法示例 返回值
DEL Deletes a key DEL KEY_NAME Number of keys removed
DEL 删除一个键 DEL KEY_NAME 被移除的键的数量
DUMP Serializes key value DUMP KEY_NAME Serialized value (String)
DUMP 序列化键值 DUMP KEY_NAME 序列化后的值 (字符串)
EXISTS Checks if key exists EXISTS KEY_NAME 1 if exists, 0 if not
EXISTS 检查键是否存在 EXISTS KEY_NAME 如果存在返回 1,否则返回 0
EXPIRE Sets key expiry (seconds) EXPIRE KEY_NAME TIME_IN_SECONDS 1 if timeout set, 0 otherwise
EXPIRE 设置键的过期时间 (秒) EXPIRE KEY_NAME TIME_IN_SECONDS 如果设置了超时返回 1,否则返回 0
PEXPIRE Sets key expiry (milliseconds) PEXPIRE KEY_NAME TIME_IN_MILLISECONDS 1 if timeout set, 0 otherwise
PEXPIRE 设置键的过期时间 (毫秒) PEXPIRE KEY_NAME TIME_IN_MILLISECONDS 如果设置了超时返回 1,否则返回 0
KEYS Lists keys matching a pattern KEYS PATTERN List of matching keys
KEYS 列出匹配模式的键 KEYS PATTERN 匹配键的列表
MOVE Moves key to another DB MOVE KEY_NAME DESTINATION_DB 1 if moved, 0 if not
MOVE 将键移动到另一个数据库 MOVE KEY_NAME DESTINATION_DB 如果移动成功返回 1,否则返回 0
PERSIST Removes expiration from a key PERSIST KEY_NAME 1 if timeout removed, 0 if not
PERSIST 移除键的过期时间 PERSIST KEY_NAME 如果移除了超时返回 1,否则返回 0
PTTL Gets remaining expiry in milliseconds PTTL KEY_NAME TTL in ms or -1 (no expiry)
PTTL 获取剩余过期时间 (毫秒) PTTL KEY_NAME 剩余生存时间 (毫秒) 或 -1 (无过期时间)
TTL Gets remaining expiry in seconds TTL KEY_NAME TTL in seconds or -1 (no expiry)
TTL 获取剩余过期时间 (秒) TTL KEY_NAME 剩余生存时间 (秒) 或 -1 (无过期时间)

5. Examples of Key Commands

5. 键命令示例

  • DEL Command:

  • DEL 命令

    1
    2
    3
    4
    127.0.0.1:6379> SET course redis
    OK
    127.0.0.1:6379> DEL course
    (integer) 1
  • EXPIRE Command:

  • EXPIRE 命令

    1
    2
    3
    4
    127.0.0.1:6379> SET course redis
    OK
    127.0.0.1:6379> EXPIRE course 60
    (integer) 1
  • KEYS Command:

  • KEYS 命令

    1
    127.0.0.1:6379> KEYS course*

6. Memory Management

6. 内存管理

  • Key Structure: Thoughtful naming and structuring of keys impacts memory usage and performance.
  • 键结构:深思熟虑的键命名和结构会影响内存使用和性能。
  • Security: Use ACLs to restrict access to keys or operations.
  • 安全:使用 ACL 来限制对键或操作的访问。

📚 Redis Key Commands

📚 Redis 键命令

🗝️ RANDOMKEY Command

🗝️ RANDOMKEY 命令

  • Purpose: Retrieves a random key from the Redis database.

  • 目的:从 Redis 数据库中检索一个随机键。

  • Return Value: A random key or nil if the database is empty.

  • 返回值:一个随机键,如果数据库为空则为 nil

  • Syntax:

  • 语法

    1
    RANDOMKEY
  • Example:

  • 示例

    1
    2
    127.0.0.1:6379> RANDOMKEY
    1) course3

✏️ RENAME Command

✏️ RENAME 命令

  • Purpose: Changes the name of an existing key.

  • 目的:更改现有键的名称。

  • Return Value: OK or error (if the old key and new key names are equal, or if the key does not exist).

  • 返回值OK 或错误(如果旧键名和新键名相同,或键不存在)。

  • Syntax:

  • 语法

    1
    RENAME OLD_KEY_NAME NEW_KEY_NAME
  • Example:

  • 示例

    1
    2
    127.0.0.1:6379> RENAME course1 course2
    OK

📊 TYPE Command

📊 TYPE 命令

  • Purpose: Returns the data type of the value stored in a key.

  • 目的:返回存储在键中的值的数据类型。

  • Return Value: The data type or none if the key does not exist.

  • 返回值:数据类型,如果键不存在则为 none

  • Syntax:

  • 语法

    1
    TYPE KEY_NAME
  • Example:

  • 示例

    1
    2
    127.0.0.1:6379> TYPE niit1
    string

🔑 Basic Redis Commands

🔑 基本 Redis 命令

Command Purpose Example
命令 目的 示例
PING Check connection to Redis Client Terminal 127.0.0.1:6379> PINGPONG
PING 检查与 Redis 客户端终端的连接 127.0.0.1:6379> PINGPONG
QUIT Exit redis-cli interface 127.0.0.1:6379> QUIT
QUIT 退出 redis-cli 界面 127.0.0.1:6379> QUIT
SET Create or overwrite a key-value pair 127.0.0.1:6379> SET name Peter
SET 创建或覆盖一个键值对 127.0.0.1:6379> SET name Peter
GET Retrieve the value for a key 127.0.0.1:6379> GET name"Peter"
GET 检索一个键的值 127.0.0.1:6379> GET name"Peter"
DEL Delete a key-value pair 127.0.0.1:6379> DEL age
DEL 删除一个键值对 127.0.0.1:6379> DEL age
EXISTS Check if a key exists 127.0.0.1:6379> EXISTS name(integer) 1
EXISTS 检查一个键是否存在 127.0.0.1:6379> EXISTS name(integer) 1
KEYS Show all keys 127.0.0.1:6379> KEYS *
KEYS 显示所有键 127.0.0.1:6379> KEYS *
FLUSHALL Delete all key-value pairs 127.0.0.1:6379> FLUSHALL
FLUSHALL 删除所有键值对 127.0.0.1:6379> FLUSHALL
TTL Set and get the time-to-live for a key 127.0.0.1:6379> TTL name
TTL 设置和获取键的生存时间 127.0.0.1:6379> TTL name
EXPIRE Set expiry time for a key 127.0.0.1:6379> EXPIRE name 6
EXPIRE 为键设置过期时间 127.0.0.1:6379> EXPIRE name 6

⚙️ Redis Architecture

⚙️ Redis 架构

  • Types:
  • 类型
    • Standalone: Small instances for speeding up services.
    • 单机版:用于加速服务的小型实例。
    • Sentinel: Monitors for failure detection via quorum.
    • 哨兵模式:通过法定数量监控故障检测。
    • Cluster: Automatically shares data across multiple nodes (horizontal scaling).
    • 集群:在多个节点间自动共享数据(水平扩展)。
  • Installation Options:
  • 安装选项
    • Using .msi installer or .zip file.
    • 使用 .msi 安装程序或 .zip 文件。

📌 Important Concepts

📌 重要概念

  • Key-Value Store: Redis stores data as key-value pairs, where retrieval requires knowing the key.
  • 键值存储:Redis 将数据存储为键值对,检索时需要知道键。
  • Data Structures: Redis supports five types: STRINGs, LISTs, SETs, HASHes, and ZSETs.
  • 数据结构:Redis 支持五种类型:字符串列表集合哈希有序集合
  • Configuration: Managed through redis.conf or via CONFIG commands.
  • 配置:通过 redis.conf 文件或 CONFIG 命令进行管理。