跳到主要内容
版本:4.1.1

Redis 专属查询方法

Doubao 中英对照 Redis-specific Query Methods

查询方法允许从方法名自动派生简单的查找查询,如下例所示:

示例 1. 仓库查找方法示例

public interface PersonRepository extends CrudRepository<Person, String> {

List<Person> findByFirstname(String firstname);
}
备注

请确保查找方法中使用的属性已设置为可索引。

备注

Redis 仓库的查询方法仅支持对实体及实体集合进行带分页的查询。

使用派生查询方法可能并不总能充分地建模要运行的查询。RedisCallback 可以对索引结构甚至自定义索引的实际匹配提供更多控制。为此,提供一个返回单个或 Iterable 的 id 值集合的 RedisCallback,如下例所示:

示例 2. 使用 RedisCallback 的查找方法示例

String user = //...

List<RedisSession> sessionsByUser = template.find(new RedisCallback<Set<byte[]>>() {

public Set<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
return connection
.sMembers("sessions:securityContext.authentication.principal.username:" + user);
}}, RedisSession.class);

下表概述了 Redis 支持的关键字,以及包含该关键字的方法本质上映射为什么:

表 1. 方法名内支持的关键字

关键字示例Redis 片段
AndfindByLastnameAndFirstnameSINTER …:firstname:rand …:lastname:al’thor
OrfindByLastnameOrFirstnameSUNION …:firstname:rand …:lastname:al’thor
Is, EqualsfindByFirstname, findByFirstnameIs, findByFirstnameEqualsSINTER …:firstname:rand
IsTrueFindByAliveIsTrueSINTER …:alive:1
IsFalsefindByAliveIsFalseSINTER …:alive:0
Top,FirstfindFirst10ByFirstname,findTop5ByFirstname

对查询方法结果排序​

Redis 仓库支持多种方式来定义排序顺序。Redis 本身在检索 hash 或 set 时不支持即时排序。因此,Redis 仓库查询方法会构造一个 Comparator,在将结果作为 List 返回之前应用于结果。请看下面的示例:

示例 3. 对查询结果排序

interface PersonRepository extends RedisRepository<Person, String> {

List<Person> findByFirstnameOrderByAgeDesc(String firstname); 1

List<Person> findByFirstname(String firstname, Sort sort); 2
}
  • 从方法名派生的静态排序。

  • 使用方法参数的动态排序。