redis-om-spring: 更好的搜尋、文件模型等的 Spring Data Redis 擴充套件

banq 發表於 2021-11-25
Redis Spring

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註釋使用手動定義的查詢。