🗄️ Redis Data Types Overview
🗄️ Redis 数据类型概述
Key Data Types in Redis:
Redis 中的关键数据类型:
- Strings (STRINGs):
- 字符串 (STRINGs):
- Stores simple text or binary data.
- 存储简单文本或二进制数据。
- Supports byte string values, integers, and floating-point values.
- 支持字节串值、整数和浮点值。
- Lists (LISTs):
- 列表 (LISTs):
- Ordered collections of strings.
- 有序的字符串集合。
- Supports operations like push, pop, and indexing.
- 支持推入、弹出和索引等操作。
- Sets (SETs):
- 集合 (SETs):
- Unordered collections of unique strings.
- 无序的唯一字符串集合。
- Operations include add, remove, and check for existence.
- 操作包括添加、删除和检查是否存在。
- Hashes (HASHes):
- 哈希 (HASHes):
- Maps fields to values, similar to objects or dictionaries.
- 将字段映射到值,类似于对象或字典。
- Ideal for storing complex data structures.
- 非常适合存储复杂的数据结构。
- Sorted Sets (ZSETs):
- 有序集合 (ZSETs):
- Similar to sets but with an associated score for each element.
- 类似于集合,但每个元素都有一个关联的分数。
- Useful for ordered data retrieval, such as leaderboards.
- 对于有序数据检索非常有用,例如排行榜。
- Geospatial Indexes:
- 地理空间索引:
- Stores and queries geospatial data (latitude and longitude).
- 存储和查询地理空间数据(纬度和经度)。
- Supports finding nearby items within a specified radius.
- 支持在指定半径内查找附近的物品。
⚙️ Common Commands for Redis Data Types
⚙️ Redis 数据类型常用命令
| Command命令 | Description描述 |
|---|---|
| GET | Fetches the data stored at the given key |
| GET | 获取给定键中存储的数据 |
| SET | Sets the value stored at the given key |
| SET | 设置给定键中存储的值 |
| DEL | Deletes the value stored at the given key |
| DEL | 删除给定键中存储的值 |
| TYPE | Checks the type of the value stored at a key |
| TYPE | 检查键中存储的值的类型 |
| RENAME | Renames a key |
| RENAME | 重命名一个键 |
STRING Commands:
字符串命令:
| Command命令 | Description描述 |
|---|---|
| SET key value | Sets the value at the specified key |
| SET key value | 设置指定键的值 |
| GET key | Gets the value of a key |
| GET key | 获取键的值 |
| INCR key | Increments the integer value of a key by one |
| INCR key | 将键的整数值增加一 |
| DECR key | Decrements the integer value of a key by one |
| DECR key | 将键的整数值减少一 |
🚀 Performance Improvement Example
🚀 性能改进示例
- Scenario: Peter’s task to redesign a client contact database used to take 15-20 seconds to query 5 million clients in MySQL.
- 场景:Peter 重新设计客户联系人数据库的任务,之前在 MySQL 中查询 500 万客户需要 15-20 秒。
- Solution: Transition to Redis to reduce response time to 50 milliseconds, improving performance by 100 times.
- 解决方案:迁移到 Redis,将响应时间减少到 50 毫秒,性能提高 100 倍。
📊 Understanding Redis String Data Types
📊 理解 Redis 字符串数据类型
STRINGs can hold:
字符串可以包含:
- Byte string values
- 字节串值
- Integer values
- 整型值
- Floating-point values
- 浮点型值
Example of STRING Operations:
字符串操作示例:
- SET Command:
- SET 命令:
127.0.0.1:6379> set hello world127.0.0.1:6379> set hello world- Returns
OK. - 返回
OK。
- GET Command:
- GET 命令:
127.0.0.1:6379> get hello127.0.0.1:6379> get hello- Returns
"world". - 返回
"world"。
- DEL Command:
- DEL 命令:
127.0.0.1:6379> del hello127.0.0.1:6379> del hello- Returns
(integer) 1. - 返回
(integer) 1。
🔍 Conclusion of Redis Data Types
🔍 Redis 数据类型总结
- Redis offers a flexible and efficient way to store and manipulate data through various types and structures.
- Redis 通过各种类型和结构提供了一种灵活高效的数据存储和操作方式。
- Understanding these data types and their commands is crucial for optimizing performance in applications that require quick data retrieval and manipulation.
- 理解这些数据类型及其命令对于优化需要快速数据检索和操作的应用程序的性能至关重要。
📊 Redis String Commands
📊 Redis 字符串命令
Key Commands
关键命令
GETRANGE
Purpose: Retrieves a substring from a string value.
目的:从字符串值中检索子字符串。
Syntax:
语法:
1
GETRANGE KEY_NAME start end
Example:
示例:
1
2
3SET mykey "This is my test key"
GETRANGE mykey 0 3 → "This"
GETRANGE mykey 0 -1 → "This is my test key"
GETSET
Purpose: Sets a new string value and returns the old value.
目的:设置新的字符串值并返回旧值。
Syntax:
语法:
1
GETSET KEY_NAME VALUE
Example:
示例:
1
GETSET mynewkey "This is my new value" → "This is my test key"
MGET
Purpose: Retrieves values for multiple keys.
目的:检索多个键的值。
Syntax:
语法:
1
MGET KEY1 KEY2 ... KEYN
Example:
示例:
1
2
3SET key1 "hello"
SET key2 "world"
MGET key1 key2 someOtherKey → 1) "hello", 2) "world", 3) (nil)
SETEX
Purpose: Sets a string value with an expiration time.
目的:设置带有过期时间的字符串值。
Syntax:
语法:
1
SETEX KEY_NAME TIMEOUT VALUE
Example:
示例:
1
2SETEX mykey 60 redis
TTL mykey → 60
SETNX
Purpose: Sets a value only if the key does not exist.
目的:仅当键不存在时才设置值。
Syntax:
语法:
1
SETNX KEY_NAME VALUE
Example:
示例:
1
2SETNX mykey redis → 1 (set)
SETNX mykey mongodb → 0 (not set)1
2SETNX mykey redis → 1 (已设置)
SETNX mykey mongodb → 0 (未设置)
STRLEN
Purpose: Returns the length of the string value.
目的:返回字符串值的长度。
Syntax:
语法:
1
STRLEN KEY_NAME
Example:
示例:
1
2SET key1 "Hello World"
STRLEN key1 → 11
MSET & MSETNX
MSET: Sets multiple values at once.
MSET:一次设置多个值。
Syntax:
语法:
1
MSET key1 value1 key2 value2 ... keyN valueN
Example:
示例:
1
MSET key1 "Hello" key2 "World" → OK
MSETNX: Sets multiple values only if none exist.
MSETNX:仅当所有键都不存在时才设置多个值。
Syntax:
语法:
1
MSETNX key1 value1 key2 value2 ... keyN valueN
Example:
示例:
1
MSETNX key1 "Hello" key2 "world" → 1
Increment and Decrement Commands
递增和递减命令
INCR: Increments the integer value by 1.
INCR:将整数值增加 1。
Example:
示例:
1
INCR visitors → 1001
INCRBY: Increments the value by a specified amount.
INCRBY:将值增加指定的量。
Example:
示例:
1
INCRBY visitors 5 → 1005
INCRBYFLOAT: Increments a floating-point number by a specified amount.
INCRBYFLOAT:将浮点数增加指定的量。
Example:
示例:
1
INCRBYFLOAT visitors 0.50 → 1000.70
DECR: Decrements the integer value by 1.
DECR:将整数值减少 1。
Example:
示例:
1
DECR visitors → 999
DECRBY: Decrements the value by a specified amount.
DECRBY:将值减少指定的量。
Example:
示例:
1
DECRBY visitors 5 → 995
Additional Notes
附加说明
String Data Type:
字符串数据类型:
- Redis strings are versatile and can store any type of data, including images and JSON.
- Redis 字符串用途广泛,可以存储任何类型的数据,包括图像和 JSON。
- Maximum length of a string is 512 MB.
- 字符串的最大长度为 512 MB。
Atomic Operations:
原子操作:
- Operations like
APPENDallow for safe concurrent modifications. - 像
APPEND这样的操作允许安全的并发修改。
- Operations like
📊 Introduction to Redis LISTs
📊 Redis 列表简介
- LISTs store an ordered sequence of STRING values and are essential for various applications like queues or lists of items.
- 列表 存储一个有序的字符串值序列,对于队列或项目列表等各种应用程序至关重要。
🔑 Basic LIST Commands
🔑 基本列表命令
| Command命令 | Action操作 |
|---|---|
| RPUSH | Pushes a value onto the right end of the list |
| RPUSH | 将一个值推入列表的右端 |
| LPOP | Pops a value from the left end of the list |
| LPOP | 从列表的左端弹出一个值 |
| LINDEX | Fetches an item at a specified position |
| LINDEX | 获取指定位置的项目 |
| LRANGE | Fetches a range of values from the list |
| LRANGE | 从列表中获取一定范围的值 |
💡 Examples of Basic Commands
💡 基本命令示例
- RPUSH:
RPUSH list-key itemreturns the current length of the list.RPUSH list-key item返回列表的当前长度。
- LRANGE:
LRANGE list-key 0 -1retrieves all items.LRANGE list-key 0 -1检索所有项目。
- LINDEX:
LINDEX list-key 1fetches the item at index 1.LINDEX list-key 1获取索引 1 处的项目。
- LPOP:
LPOP list-keyremoves the first item and returns it.LPOP list-key删除第一个项目并返回它。
🔍 Advanced LIST Commands
🔍 高级列表命令
| Command命令 | Description描述 |
|---|---|
| BLPOP | Blocks until the first element is available |
| BLPOP | 阻塞直到第一个元素可用 |
| BRPOP | Blocks until the last element is available |
| BRPOP | 阻塞直到最后一个元素可用 |
| BRPOPLPUSH | Moves an element from one list to another |
| BRPOPLPUSH | 将元素从一个列表移动到另一个列表 |
| LINSERT | Inserts an element before/after a specified pivot |
| LINSERT | 在指定基准元素之前/之后插入一个元素 |
| LLEN | Gets the length of a list |
| LLEN | 获取列表的长度 |
| LREM | Removes specified occurrences of an element |
| LREM | 删除指定出现次数的元素 |
| LTRIM | Trims the list to a specific range |
| LTRIM | 将列表修剪到特定范围 |
🧩 Detailed Command Descriptions
🧩 详细命令描述
- BLPOP:
- BLPOP:
- Syntax:
BLPOP LIST1 LIST2 ... TIMEOUT - 语法:
BLPOP LIST1 LIST2 ... TIMEOUT - Returns the first element or blocks until one is available.
- 返回第一个元素,或者阻塞直到有元素可用。
- Syntax:
- BRPOP:
- BRPOP:
- Syntax:
BRPOP LIST1 LIST2 ... TIMEOUT - 语法:
BRPOP LIST1 LIST2 ... TIMEOUT - Functions like BLPOP but for the last element.
- 功能类似 BLPOP,但针对最后一个元素。
- Syntax:
- LINSERT:
- LINSERT:
- Syntax:
LINSERT KEY_NAME BEFORE|AFTER PIVOT VALUE - 语法:
LINSERT KEY_NAME BEFORE|AFTER PIVOT VALUE - Adds a new value relative to an existing value.
- 相对于现有值添加一个新值。
- Syntax:
- LLEN:
- LLEN:
- Syntax:
LLEN KEY_NAME - 语法:
LLEN KEY_NAME - Returns the number of items in the list.
- 返回列表中的项目数。
- Syntax:
- LREM:
- LREM:
- Syntax:
LREM KEY_NAME COUNT VALUE - 语法:
LREM KEY_NAME COUNT VALUE - Removes items based on the count specified (positive, negative, or zero).
- 根据指定的计数(正数、负数或零)删除项目。
- Syntax:
- LSET:
- LSET:
- Syntax:
LSET KEY_NAME INDEX VALUE - 语法:
LSET KEY_NAME INDEX VALUE - Sets a value at a specific index.
- 在特定索引处设置一个值。
- Syntax:
- LTRIM:
- LTRIM:
- Syntax:
LTRIM KEY_NAME START STOP - 语法:
LTRIM KEY_NAME START STOP - Reduces the list to a specified range.
- 将列表缩减到指定的范围。
- Syntax:
🛠️ Practical Command Examples
🛠️ 实际命令示例
- LINSERT:
- LINSERT:
LINSERT list1 BEFORE "bar" "Yes"results in adding “Yes” before “bar”.LINSERT list1 BEFORE "bar" "Yes"会在 “bar” 之前添加 “Yes”。
- LREM:
- LREM:
LREM mylist -2 "hello"removes the first two occurrences of “hello”.LREM mylist -2 "hello"删除 “hello” 的前两次出现。
- LTRIM:
- LTRIM:
LTRIM mylist 1 -1trims the list to include elements from index 1 to the end.LTRIM mylist 1 -1将列表修剪为包含从索引 1 到末尾的元素。
Redis LISTs provide a versatile way to manage ordered collections of strings, making them useful for a variety of applications in programming and data management.
Redis 列表提供了一种管理有序字符串集合的通用方法,使其在编程和数据管理的各种应用中非常有用。
🗂️ Redis Data Structures
🗂️ Redis 数据结构
📜 Redis Lists
📜 Redis 列表
Definition: An ordered collection of strings.
定义:一个有序的字符串集合。
Key Characteristics:
主要特征:
- Maintains insertion order.
- 保持插入顺序。
- Allows duplicate elements.
- 允许重复元素。
Key Commands:
关键命令:
Command 命令 Description 描述 RPUSH Add an item to the end of the list RPUSH 将项目添加到列表末尾 RPOPLPUSH Remove the last item and push it to another list RPOPLPUSH 移除最后一个项目并将其推送到另一个列表 LRANGE Get a range of elements from the list LRANGE 从列表中获取一定范围的元素 Example:
示例:
1
2127.0.0.1:6379> RPUSH mylist "hello"
(integer) 1
🍃 Redis Sets
🍃 Redis 集合
Definition: An unordered collection of unique strings.
定义:一个无序的唯一字符串集合。
Key Characteristics:
主要特征:
- No duplicate elements.
- 没有重复元素。
- Unordered; cannot push/pop from ends.
- 无序;不能从两端推入/弹出。
Key Commands:
关键命令:
| Command 命令 | Description 描述 |
|---|---|
| SADD | Add items to the set |
| SADD | 向集合中添加项目 |
| SMEMBERS | Fetch all items in the set |
| SMEMBERS | 获取集合中的所有项目 |
| SISMEMBER | Check if an item exists in the set |
| SISMEMBER | 检查项目是否存在于集合中 |
| SREM | Remove an item from the set |
| SREM | 从集合中移除一个项目 |
Example:
示例:
1
2127.0.0.1:6379> SADD myset "hello"
(integer) 1
🔑 Advanced Set Commands
🔑 高级集合命令
Common Commands:
常用命令:
| Command 命令 | Description 描述 |
|---|---|
| SCARD key | Get number of members in a set |
| SCARD key | 获取集合中成员的数量 |
| SRANDMEMBER key | Get a random member from the set |
| SRANDMEMBER key | 从集合中获取一个随机成员 |
| SPOP key | Remove and return a random member |
| SPOP key | 移除并返回一个随机成员 |
| SMOVE source dest member | Move a member from one set to another |
| SMOVE source dest member | 将一个成员从一个集合移动到另一个集合 |
| SUNION key1 [key2] | Returns the union of multiple sets |
| SUNION key1 [key2] | 返回多个集合的并集 |
🔄 List vs. Set Comparison
🔄 列表与集合比较
| Feature特性 | Lists列表 | Sets集合 |
|---|---|---|
| Order | Maintains order | No specific order |
| 顺序 | 保持顺序 | 没有特定顺序 |
| Duplicates | Allows duplicates | Unique elements only |
| 重复项 | 允许重复 | 仅唯一元素 |
| Access Method | Index-based access | Value-based access |
| 访问方法 | 基于索引的访问 | 基于值的访问 |
🛠️ Practical Use Cases
🛠️ 实际使用案例
- Lists: Ideal for message queues, stacks, and ordered collections.
- 列表:非常适合消息队列、堆栈和有序集合。
- Sets: Useful for membership testing, managing unique items, and performing set operations (intersection, union).
- 集合:用于成员资格测试、管理唯一项目以及执行集合操作(交集、并集)。
🧩 Redis Data Types
🧩 Redis 数据类型
📦 Sets
📦 集合
Definition: A collection of unique items.
定义:一个唯一项目的集合。
Usage: Ideal for storing unique identifiers, tags, etc.
用途:非常适合存储唯一标识符、标签等。
Memory Efficiency: Prevents duplicate entries.
内存效率:防止重复条目。
Supported Operations:
支持的操作:
- Union
- 并集
- Intersection
- 交集
- Difference
- 差集
📊 Hashes
📊 哈希
Hashes are mappings of keys to values, similar to objects or dictionaries in programming.
哈希是键到值的映射,类似于编程中的对象或字典。
Commands:
命令:
- HSET: Stores a value at a specified key in the hash.
- HSET:在哈希中指定键处存储一个值。
- HGET: Retrieves a value using a specified hash key.
- HGET:使用指定的哈希键检索一个值。
- HGETALL: Fetches all items in the hash.
- HGETALL:获取哈希中的所有项目。
- HDEL: Removes a specified key from the hash.
- HDEL:从哈希中移除指定的键。
Example Commands:
示例命令:
1 | 127.0.0.1:6379> hset hash-key sub-key1 value1 |
Advanced Commands:
高级命令:
- HEXISTS: Checks if a hash field exists.
- HEXISTS:检查哈希字段是否存在。
- HKEYS: Gets all field names in the hash.
- HKEYS:获取哈希中的所有字段名。
- HVALS: Gets all values in the hash.
- HVALS:获取哈希中的所有值。
- HINCRBY: Increments an integer value in the hash.
- HINCRBY:增加哈希中整数的值。
- HINCRBYFLOAT: Increments a float value in the hash.
- HINCRBYFLOAT:增加哈希中浮点数的值。
🎯 Sorted Sets (ZSETs)
🎯 有序集合 (ZSETs)
Definition: Similar to hashes, but with unique members and scores (floating-point numbers).
定义:类似于哈希,但具有唯一的成员和分数(浮点数)。
Commands:
命令:
- ZADD: Adds a member with a score to the ZSET.
- ZADD:将带有分数的成员添加到有序集合。
- ZRANGE: Fetches items in sorted order.
- ZRANGE:按排序顺序获取项目。
- ZREM: Removes an item from the ZSET.
- ZREM:从有序集合中移除一个项目。
Example Commands:
示例命令:
1 | 127.0.0.1:6379> zadd zset-key 728 member1 |
Advanced Commands:
高级命令:
- ZCARD: Gets the number of members in a sorted set.
- ZCARD:获取有序集合中成员的数量。
- ZINCRBY: Increments the score of a member.
- ZINCRBY:增加成员的分数。
- ZRANK: Determines the index of a member in the sorted set.
- ZRANK:确定成员在有序集合中的索引。
🔑 Key Takeaways
🔑 关键要点
- Memory Efficiency: Redis data types are optimized for performance and memory usage.
- 内存效率:Redis 数据类型针对性能和内存使用进行了优化。
- Complex Structures: HASHes and ZSETs allow for structured data storage and efficient retrieval.
- 复杂结构:哈希和有序集合允许结构化数据存储和高效检索。
- Versatile Commands: Redis provides a comprehensive command set for managing data effectively across various types.
- 通用命令:Redis 提供了一套全面的命令集,用于跨各种类型有效地管理数据。
🛠️ Redis Commands Overview
🛠️ Redis 命令概述
1. ZCARD Command
1. ZCARD 命令
ZCARD returns the number of elements in a sorted set.
ZCARD 返回有序集合中元素的数量。
Syntax:
ZCARD KEY_NAME语法:
ZCARD KEY_NAMEExample:
示例:
1
2127.0.0.1:6379> ZCARD myzset
(integer) 4
2. ZINCRBY Command
2. ZINCRBY 命令
ZINCRBY increments the score of a member in a sorted set.
ZINCRBY 增加有序集合中成员的分数。
If the member does not exist, it is added with the increment as its score.
如果成员不存在,则会添加该成员,并将增量作为其分数。
Syntax:
ZINCRBY KEY INCREMENT MEMBER语法:
ZINCRBY KEY INCREMENT MEMBERExample:
示例:
1
2127.0.0.1:6379> ZINCRBY myzset 2 "hello"
(integer) 3
3. ZCOUNT Command
3. ZCOUNT 命令
ZCOUNT returns the number of elements in a sorted set with scores between the specified minimum and maximum.
ZCOUNT 返回有序集合中分数在指定最小值和最大值之间的元素数量。
Syntax:
ZCOUNT KEY_NAME MIN MAX语法:
ZCOUNT KEY_NAME MIN MAXExample:
示例:
1
2127.0.0.1:6379> ZCOUNT myzset (1 3
(integer) 2
4. ZRANK Command
4. ZRANK 命令
ZRANK returns the rank of a member in a sorted set, with scores ordered from low to high.
ZRANK 返回成员在有序集合中的排名,分数从低到高排序。
Syntax:
ZRANK key member语法:
ZRANK key memberExample:
示例:
1
2127.0.0.1:6379> ZRANK myzset b
(integer) 1
5. ZSCORE Command
5. ZSCORE 命令
ZSCORE returns the score of a member in the sorted set.
ZSCORE 返回有序集合中成员的分数。
Syntax:
ZSCORE key member语法:
ZSCORE key memberExample:
示例:
1
2127.0.0.1:6379> ZSCORE myzset "c"
(integer) 3
📊 Redis Sorted Sets (ZSETS)
📊 Redis 有序集合 (ZSETS)
Definition: Sorted Sets are a data structure that stores unique members with associated scores, determining their order.
定义:有序集合是一种数据结构,用于存储具有关联分数的唯一成员,这些分数决定了它们的顺序。
Characteristics:
特性:
- Only unique members (no duplicates)
- 仅唯一成员(无重复)
- Ideal for leaderboards, priority queues, and ordered data scenarios
- 非常适合排行榜、优先级队列和有序数据场景
- Memory-efficient, especially for members with the same score
- 内存效率高,特别是对于具有相同分数的成员
🖥️ Connecting to Redis in Java using Jedis
🖥️ 使用 Jedis 在 Java 中连接到 Redis
Setup Steps:
设置步骤:
Include the Redis Java client library:
包含 Redis Java 客户端库:
1
2
3
4
5<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>Connect to Redis Server:
连接到 Redis 服务器:
1
Jedis jedis = new Jedis("localhost");
Store and Retrieve Data:
存储和检索数据:
Store a string:
存储字符串:
1
jedis.set("message", "Hello, Redis!");
Retrieve the string:
检索字符串:
1
String message = jedis.get("message");
⚙️ Troubleshooting Common Issues
⚙️ 常见问题故障排除
- Connection Issues:
- 连接问题:
- Ensure the Redis server is running and accessible.
- 确保 Redis 服务器正在运行且可访问。
- Performance Issues:
- 性能问题:
- Monitor performance and optimize operations as needed.
- 监控性能并根据需要优化操作。
- Data Consistency:
- 数据一致性:
- Redis provides eventual consistency; consider transactions for strong consistency.
- Redis 提供最终一致性;对于强一致性,请考虑使用事务。
- Memory Management:
- 内存管理:
- Monitor memory usage and enable eviction policies if necessary.
- 监控内存使用情况,并在必要时启用逐出策略。
- Data Persistence:
- 数据持久化:
- Enable persistence options like RDB snapshots or AOF logs to prevent data loss.
- 启用 RDB 快照或 AOF 日志等持久化选项以防止数据丢失。
📋 Activity 7.1: Practice Connecting Redis in Java
📋 活动 7.1:练习在 Java 中连接 Redis
- Write a Java program to connect to a Redis server, execute commands like
PING,SET, andGET, and display results. Use the provided code snippet as a reference. - 编写一个 Java 程序连接到 Redis 服务器,执行
PING、SET和GET等命令,并显示结果。使用提供的代码片段作为参考。
🛠️ Working with Redis Data Types & Geospatial Data
🛠️ 使用 Redis 数据类型和地理空间数据
Introduction to Redis
Redis 简介
- Redis: An open-source key-value data store known for its speed and efficiency.
- Redis:一个以速度和效率著称的开源键值数据存储。
- Common Uses: Caching, session management, gaming, analytics, and geospatial data.
- 常见用途:缓存、会话管理、游戏、分析和地理空间数据。
💻 Connecting Java to Redis
💻 将 Java 连接到 Redis
Code Example:
代码示例:
1
2Jedis jedis = new Jedis("localhost");
System.out.println("The server is running " + jedis.ping());Key Points:
关键点:
- Use Jedis class to connect Java programs to Redis.
- 使用 Jedis 类将 Java 程序连接到 Redis。
jedis.set("company-name", "NIIT LTD"): Store a key-value pair.jedis.set("company-name", "NIIT LTD"):存储一个键值对。jedis.get("company-name"): Retrieve the value associated with the key.jedis.get("company-name"):检索与键关联的值。
🌍 Geospatial Data in Redis
🌍 Redis 中的地理空间数据
- Challenges: Latitude and longitude are complex due to Earth’s curvature; precision is critical.
- 挑战:由于地球曲率,纬度和经度很复杂;精度至关重要。
- Geohash: Represents coordinates as a string using Base32 encoding. Shorter geohashes provide less precision.
- Geohash:使用 Base32 编码将坐标表示为字符串。较短的 geohash 提供较低的精度。
Storage of Geospatial Data
地理空间数据的存储
- Utilizes sorted sets (ZSET) for geospatial data storage.
- 利用有序集合 (ZSET) 进行地理空间数据存储。
- Geo Set: Data structure managing geospatial indexes with unique identifiers and coordinate pairs.
- 地理集合:管理带有唯一标识符和坐标对的地理空间索引的数据结构。
📊 Geospatial Commands in Redis
📊 Redis 中的地理空间命令
Key Commands:
关键命令:
| Command命令 | Description描述 |
|---|---|
| GEOADD | Adds new elements or updates existing ones in a Geo Set. |
| GEOADD | 在地理集合中添加新元素或更新现有元素。 |
| ZREM | Removes entries from a Geo Set. |
| ZREM | 从地理集合中删除条目。 |
| DEL | Deletes a geo index (not recommended for large lists). |
| DEL | 删除地理索引(不建议用于大型列表)。 |
| UNLINK | Non-blocking delete for a geo index. |
| UNLINK | 地理索引的非阻塞删除。 |
| EXPIRE | Sets an expiration time for an index. |
| EXPIRE | 为索引设置过期时间。 |
| GEOPOS | Retrieves coordinates of an entry. |
| GEOPOS | 检索条目的坐标。 |
| GEODIST | Calculates distance between two entries. |
| GEODIST | 计算两个条目之间的距离。 |
| GEORADIUS | Retrieves entries within a specified radius. |
| GEORADIUS | 检索指定半径内的条目。 |
📏 Reading Locations and Distances
📏 读取位置和距离
Get Coordinates:
获取坐标:
1
GEOPOS buses "Bus A"
Get Geohash:
获取 Geohash:
1
GEOHASH buses "Bus A"
Calculate Distance:
计算距离:
1
GEODIST buses "Bus A" "Bus B"
🔍 Searching with Geospatial Data
🔍 使用地理空间数据进行搜索
Find Nearby Buses:
查找附近的公交车:
1
GEORADIUS buses -73 40 200 km WITHDIST
🗄️ Redis Data Structures
🗄️ Redis 数据结构
1. Overview of Redis Data Types
1. Redis 数据类型概述
- Redis supports five primary data structures:
- Redis 支持五种主要数据结构:
- Strings (STRINGs)
- 字符串 (STRINGs)
- Lists (LISTs)
- 列表 (LISTs)
- Sets (SETs)
- 集合 (SETs)
- Hashes (HASHes)
- 哈希 (HASHes)
- Sorted Sets (ZSETs)
- 有序集合 (ZSETs)
2. Strings (STRINGs)
2. 字符串 (STRINGs)
Strings are versatile data structures capable of storing any type of data, including text, images, and JSON.
字符串是通用的数据结构,能够存储任何类型的数据,包括文本、图像和 JSON。
- Characteristics:
- 特性:
- Maximum length: 512 MB
- 最大长度:512 MB
- Binary-safe: Can hold any binary data
- 二进制安全:可以保存任何二进制数据
- Common Commands:
- 常用命令:
SET,GET,MSET,INCR,DECR,APPEND,STRLEN,GETRANGESET,GET,MSET,INCR,DECR,APPEND,STRLEN,GETRANGE
3. Lists (LISTs)
3. 列表 (LISTs)
Lists are ordered collections of strings that maintain insertion order.
列表是维护插入顺序的有序字符串集合。
- Characteristics:
- 特性:
- Can contain duplicates
- 可以包含重复项
- Dynamic size (grows/shrinks as needed)
- 动态大小(根据需要增长/缩小)
- Push and Pop Operations:
- 推入和弹出操作:
LPUSH: Insert at the headLPUSH:在头部插入RPUSH: Insert at the tailRPUSH:在尾部插入LPOP: Remove first elementLPOP:移除第一个元素RPOP: Remove last elementRPOP:移除最后一个元素
- Common Commands:
- 常用命令:
LRANGE,LLEN,LINSERT,LREMLRANGE,LLEN,LINSERT,LREM
4. Sets (SETs)
4. 集合 (SETs)
Sets are unordered collections of unique strings, automatically enforcing uniqueness.
集合是无序的唯一字符串集合,自动强制唯一性。
- Characteristics:
- 特性:
- No defined order for elements
- 元素没有定义的顺序
- Memory-efficient for unique data
- 对于唯一数据而言内存效率高
- Common Commands:
- 常用命令:
SADD,SREM,SISMEMBER,SCARD,SUNION,SINTERSADD,SREM,SISMEMBER,SCARD,SUNION,SINTER
5. Hashes (HASHes)
5. 哈希 (HASHes)
Hashes represent maps of fields and values, similar to dictionaries in programming.
哈希表示字段和值的映射,类似于编程中的字典。
- Characteristics:
- 特性:
- Fields within a hash are unordered
- 哈希内的字段是无序的
- Unique fields only (no duplicates)
- 仅唯一字段(无重复)
- Common Commands:
- 常用命令:
HSET,HGET,HMGET,HDEL,HINCRBYHSET,HGET,HMGET,HDEL,HINCRBY
6. Sorted Sets (ZSETs)
6. 有序集合 (ZSETs)
Sorted Sets store unique members with associated scores for ordering.
有序集合存储唯一的成员及其关联的分数以进行排序。
- Characteristics:
- 特性:
- Members are ordered by their scores (floating-point numbers)
- 成员按其分数(浮点数)排序
- Supports efficient range queries
- 支持高效的范围查询
- Common Commands:
- 常用命令:
ZADD,ZREM,ZCARD,ZRANGE,ZRANKZADD,ZREM,ZCARD,ZRANGE,ZRANK
7. Working with Redis in Java
7. 在 Java 中使用 Redis
To connect to Redis using Java:
使用 Java 连接到 Redis:
1
Jedis jedis = new Jedis("localhost");
Use the Jedis library for a low-level API to interact with Redis.
使用 Jedis 库通过低级 API 与 Redis 交互。
8. Geospatial Data
8. 地理空间数据
Geohash encodes latitude and longitude into a string format.
Geohash 将纬度和经度编码为字符串格式。
- Common Commands for geospatial data:
- 地理空间数据的常用命令:
GEOADD,GEODIST,GEORADIUS,GEORADIUSBYMEMBERGEOADD,GEODIST,GEORADIUS, `GEORADIUSBYMEMBER