跳到主要内容

Redis 仓库解析

DeepSeek V3 中英对照 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;
}
java

插入新数据

repository.save(new Person("rand", "al'thor"));
java
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>
text
  • 将扁平化的条目保存为哈希。

  • 将 <1> 中写入的哈希键添加到同一键空间中实体的辅助索引中。

  • 将 <2> 中写入的哈希键添加到带有属性值的 firstnames 的二级索引中。

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

替换现有的

repository.save(new Person("e82908cf-e7d3-47c2-9eec-b4e0967ad0c9", "Dragon Reborn", "al'thor"));
java
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>
text
  • 移除现有的哈希,以避免可能存在不再存在的哈希键残留。

  • 将扁平化的条目保存为哈希。

  • 将<1>中写入的哈希键添加到同一键空间中实体的辅助索引中。

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

  • 检查索引是否存在以及它的类型(文本、地理位置等)。

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

  • 移除保存索引信息的辅助结构。

  • 将<2>中添加的哈希键添加到具有属性值的名字的二级索引中。

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

保存地理数据

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

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>
text
  • 将已保存条目的键添加到地理索引中。

  • 跟踪索引结构。

使用简单索引查找

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

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

使用地理索引查找

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

  • 逐个获取由 <1> 返回的每个键。