跳到主要内容
版本:4.1.1

Redis 仓库剖析

Doubao 中英对照 Redis Repositories Anatomy

Redis 作为存储本身仅提供非常狭窄的底层 API,将二级索引和查询操作等更高级别的功能留给用户自行实现。

本节更详细地介绍仓库抽象发出的命令,以便更好地理解其潜在的性能影响。

以下面的实体类作为所有操作的起点:

示例 1. 示例实体

@RedisHash("people")
public class Person {

@Id String id;
@Indexed String firstname;
String lastname;
Address hometown;
}

public class Address {

@GeoIndexed Point location;
}

插入新数据​

repository.save(new Person("rand", "al'thor"));
HMSET "people:19315449-cda2-4f5c-b696-9cb8018fa1f9" "_class" "Person" "id" "19315449-cda2-4f5c-b696-9cb8018fa1f9" "firstname" "rand" "lastname" "al'thor" // <1>
SADD "people" "19315449-cda2-4f5c-b696-9cb8018fa1f9" // <2>
SADD "people:firstname:rand" "19315449-cda2-4f5c-b696-9cb8018fa1f9" // <3>
SADD "people:19315449-cda2-4f5c-b696-9cb8018fa1f9:idx" "people:firstname:rand" // <4>
  • 将扁平化后的条目保存为 hash。

  • 将在 <1> 中写入的 hash 的键添加到同一 keyspace 内实体的辅助索引。

  • 将在 <2> 中写入的 hash 的键按属性值添加到 firstname 的二级索引。

  • 将 <3> 的索引添加到该条目的辅助结构集合中,以便在删除/更新时跟踪需要清理的索引。

替换已有数据​

repository.save(new Person("e82908cf-e7d3-47c2-9eec-b4e0967ad0c9", "Dragon Reborn", "al'thor"));
DEL       "people:e82908cf-e7d3-47c2-9eec-b4e0967ad0c9"                           // <1>
HMSET "people:e82908cf-e7d3-47c2-9eec-b4e0967ad0c9" "_class" "Person" "id" "e82908cf-e7d3-47c2-9eec-b4e0967ad0c9" "firstname" "Dragon Reborn" "lastname" "al'thor" // <2>
SADD "people" "e82908cf-e7d3-47c2-9eec-b4e0967ad0c9" // <3>
SMEMBERS "people:e82908cf-e7d3-47c2-9eec-b4e0967ad0c9:idx" // <4>
TYPE "people:firstname:rand" // <5>
SREM "people:firstname:rand" "e82908cf-e7d3-47c2-9eec-b4e0967ad0c9" // <6>
DEL "people:e82908cf-e7d3-47c2-9eec-b4e0967ad0c9:idx" // <7>
SADD "people:firstname:Dragon Reborn" "e82908cf-e7d3-47c2-9eec-b4e0967ad0c9" // <8>
SADD "people:e82908cf-e7d3-47c2-9eec-b4e0967ad0c9:idx" "people:firstname:Dragon Reborn" // <9>
  • 删除已有的 hash,以避免残留可能不再存在的 hash 键。

  • 将扁平化后的条目保存为 hash。

  • 将在 <1> 中写入的 hash 的键添加到同一 keyspace 内实体的辅助索引。

  • 获取可能需要更新的已有索引结构。

  • 检查索引是否存在及其类型(text、geo、…)。

  • 从索引中移除可能已存在的键。

  • 移除持有索引信息的辅助结构。

  • 将在 <2> 中添加的 hash 的键按属性值添加到 firstname 的二级索引。

  • 将 <6> 的索引添加到该条目的辅助结构集合中,以便在删除/更新时跟踪需要清理的索引。

保存 Geo 数据​

Geo 索引遵循与普通文本索引相同的规则,但使用 geo 结构来存储值。保存使用 Geo 索引属性的实体会产生以下命令:

GEOADD "people:hometown:location" "13.361389" "38.115556" "76900e94-b057-44bc-abcf-8126d51a621b"  // <1>
SADD "people:76900e94-b057-44bc-abcf-8126d51a621b:idx" "people:hometown:location" // <2>
  • 将已保存条目的键添加到 geo 索引。

  • 跟踪该索引结构。

使用简单索引查找​

repository.findByFirstname("egwene");
SINTER  "people:firstname:egwene"                     // <1>
HGETALL "people:d70091b5-0b9a-4c0a-9551-519e61bc9ef3" // <2>
HGETALL ...
  • 获取二级索引中包含的键。

  • 单独获取 <1> 返回的每个键。

使用 Geo 索引查找​

repository.findByHometownLocationNear(new Point(15, 37), new Distance(200, KILOMETERS));
GEORADIUS "people:hometown:location" "15.0" "37.0" "200.0" "km" // <1>
HGETALL "people:76900e94-b057-44bc-abcf-8126d51a621b" // <2>
HGETALL ...
  • 获取二级索引中包含的键。

  • 单独获取 <1> 返回的每个键。