对于最新稳定版本,请使用 Spring Data Couchbase 6.0.4spring-doc.cadn.net.cn

响应式 Couchbase 仓库

介绍

本章介绍 Couchbase 的响应式仓库支持。 它建立在 Couchbase 仓库 中解释的核心仓库支持之上。 因此,请确保您已充分理解其中阐述的基本概念。spring-doc.cadn.net.cn

响应式组合库

Couchbase Java SDK 3.x 已从 RxJava 迁移到 Reactor,因此它与响应式 Spring 生态系统非常契合。spring-doc.cadn.net.cn

响应式 Couchbase 仓库提供 Project Reactor 包装类型,可以通过直接扩展特定库的仓库接口之一来使用:spring-doc.cadn.net.cn

用法

让我们先创建一个简单的实体:spring-doc.cadn.net.cn

示例 1. 示例 Person 实体
public class Person {

  @Id
  private String id;
  private String firstname;
  private String lastname;
  private Address address;

  // … getters and setters omitted
}

一个对应的仓库实现可能如下所示:spring-doc.cadn.net.cn

示例 2. 用于持久化 Person 实体的基本 Repository 接口
public interface ReactivePersonRepository extends ReactiveSortingRepository<Person, Long> {

  Flux<Person> findByFirstname(String firstname);

  Flux<Person> findByFirstname(Publisher<String> firstname);

  Flux<Person> findByFirstnameOrderByLastname(String firstname, Pageable pageable);

  Mono<Person> findByFirstnameAndLastname(String firstname, String lastname);
}

对于 JavaConfig,请使用 @EnableReactiveCouchbaseRepositories 注解。 该注解拥有与命名空间元素完全相同的属性。 如果未配置基础包,基础设施将扫描已注解配置类所在的包。spring-doc.cadn.net.cn

另外请注意,如果您在 Spring Boot 设置中使用它,可能可以省略该注解,因为它已为您自动配置。spring-doc.cadn.net.cn

示例 3. 仓库的 JavaConfig
@Configuration
@EnableReactiveCouchbaseRepositories
class ApplicationConfig extends AbstractCouchbaseConfiguration {
	// ... (see configuration for details)
}

由于我们的域仓库继承自 ReactiveSortingRepository,它为您提供 CRUD 操作以及用于有序访问实体的方法。 使用仓库实例只需将其依赖注入到客户端即可。spring-doc.cadn.net.cn

示例 4. 对 Person 实体进行排序访问
public class PersonRepositoryTests {

    @Autowired
    ReactivePersonRepository repository;

    @Test
    public void sortsElementsCorrectly() {
      Flux<Person> persons = repository.findAll(Sort.by(new Order(ASC, "lastname")));
      assertNotNull(perons);
    }
}

仓库与查询

Spring Data 的响应式 Couchbase 已经通过阻塞式的仓储与查询提供了完整的查询支持spring-doc.cadn.net.cn