redis-om-spring: 更好的搜索、文档模型等的 Spring Data Redis 扩展

21-11-25 banq

Redis OM Spring扩展了Spring Data Redis以充分利用 Redis 的强大功能。

Redis OM Spring 提供强大的存储库和自定义对象映射抽象,这些抽象构建在强大的 Spring Data Redis (SDR) 框架之上。

 

添加Maven依赖:

<dependency>
  <groupId>com.redis.om.spring</groupId>
  <artifactId>redis-om-spring</artifactId>
  <version>${version}</version>
</dependency>

主应用:

@SpringBootApplication
@Configuration
@EnableRedisDocumentRepositories(basePackages = "com.redis.documents.*")
public class RdsDocumentsApplication {

  @Autowired
  CompanyRepository companyRepo;

  @Bean
  CommandLineRunner loadTestData() {
    return args -> {
      companyRepo.deleteAll();
      Company redis = Company.of(
        "Redis", "https://redis.com", new Point(-122.066540, 37.377690), 526, 2011 //
      );
      redis.setTags(Set.of("fast", "scalable", "reliable"));

      Company microsoft = Company.of(
        "Microsoft", "https://microsoft.com", new Point(-122.124500, 47.640160), 182268, 1975 //
      );
      microsoft.setTags(Set.of("innovative", "reliable"));
    };
  }

  public static void main(String[] args) {
    SpringApplication.run(RdsDocumentsApplication.class, args);
  }
}

  • @EnableRedisDocumentRepositories使用 Repository 接口自动实现复杂的查询功能 

 

实体类:

@Data
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
@Document
public class Company {
  @Id private String id;
  @Searchable private String name;
  @Indexed private Point location;
  @Indexed private Set<String> tags = new HashSet<String>();
  @Indexed private Integer numberOfEmployees;
  @Indexed private Integer yearFounded;
  private String url;
  private boolean publiclyListed;

  // ...

  • @Document 将 Spring Data 模型映射到 Redis JSON 文档的注释

  • 声明式搜索索引通过 @Indexable
  • 全文检索索引通过 @Searchable

 

仓储接口:

public interface CompanyRepository extends RedisDocumentRepository<Company, String> {
  // find one by property
  Optional<Company> findOneByName(String name);

  // geospatial query
  Iterable<Company> findByLocationNear(Point point, Distance distance);

  // find by tag field, using JRediSearch "native" annotation
  @Query("@tags:{$tags}")
  Iterable<Company> findByTags(@Param("tags") Set<String> tags);

  // find by numeric property
  Iterable<Company> findByNumberOfEmployees(int noe);

  // find by numeric property range
  Iterable<Company> findByNumberOfEmployeesBetween(int noeGT, int noeLT);

  // starting with/ending with
  Iterable<Company> findByNameStartingWith(String prefix);
}

存储库代理有两种方法可以从方法名称派生特定于商店的查询:

  • 通过直接从方法名称派生查询。
  • 通过使用@Query或@Aggregation注释使用手动定义的查询。

猜你喜欢