MongoDB
 sql >> Cơ Sở Dữ Liệu >  >> NoSQL >> MongoDB

Kho lưu trữ phản ứng dữ liệu mùa xuân với MongoDB

1. Giới thiệu

Trong hướng dẫn này, chúng ta sẽ xem cách định cấu hình và triển khai các hoạt động cơ sở dữ liệu bằng cách sử dụng Lập trình phản ứng thông qua Kho lưu trữ phản ứng dữ liệu mùa xuân với MongoDB.

Chúng ta sẽ xem xét các cách sử dụng cơ bản của ReactiveCrud Kho lưu trữ, ReactiveMongoRepository , cũng như ReactiveMongoTemplate.

Mặc dù những triển khai này sử dụng lập trình phản ứng, nhưng đó không phải là trọng tâm chính của hướng dẫn này.

2. Môi trường

Để sử dụng Reactive MongoDB, chúng ta cần thêm phần phụ thuộc vào pom.xml.

Chúng tôi cũng sẽ thêm một MongoDB được nhúng để thử nghiệm:

<dependencies>
    // ...
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
    </dependency>
    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3. Cấu hình

Để kích hoạt hỗ trợ phản ứng, chúng tôi cần sử dụng @EnableReactiveMongoRepositories cùng với một số thiết lập cơ sở hạ tầng:

@EnableReactiveMongoRepositories
public class MongoReactiveApplication
  extends AbstractReactiveMongoConfiguration {

    @Bean
    public MongoClient mongoClient() {
        return MongoClients.create();
    }

    @Override
    protected String getDatabaseName() {
        return "reactive";
    }
}

Lưu ý rằng những điều trên là cần thiết nếu chúng tôi đang sử dụng cài đặt MongoDB độc lập. Tuy nhiên, vì chúng tôi đang sử dụng Spring Boot có nhúng MongoDB trong ví dụ của chúng tôi, nên cấu hình trên là không cần thiết.

4. Tạo Tài liệu

Đối với các ví dụ bên dưới, hãy tạo một Tài khoản và chú thích nó bằng @Document để sử dụng nó trong các hoạt động cơ sở dữ liệu:

@Document
public class Account {
 
    @Id
    private String id;
    private String owner;
    private Double value;
 
    // getters and setters
}

5. Sử dụng Kho lưu trữ phản ứng

Chúng ta đã quen thuộc với mô hình lập trình kho lưu trữ, với các phương thức CRUD đã được xác định cộng với hỗ trợ cho một số thứ phổ biến khác.

Bây giờ với mô hình Reactive, chúng tôi nhận được cùng một tập hợp các phương pháp và thông số kỹ thuật, ngoại trừ việc chúng tôi sẽ xử lý các kết quả và thông số theo cách phản ứng.

5.1. ReactiveCrudRepository

Chúng tôi có thể sử dụng hệ thống lưu trữ này giống như cách chặn CrudRepository :

@Repository
public interface AccountCrudRepository 
  extends ReactiveCrudRepository<Account, String> {
 
    Flux<Account> findAllByValue(String value);
    Mono<Account> findFirstByOwner(Mono<String> owner);
}

Chúng tôi có thể chuyển các loại đối số khác nhau như đơn giản ( Chuỗi ), được bọc ( Tùy chọn , Luồng ) hoặc phản ứng ( Mono , Flux ) như chúng ta có thể thấy trong findFirstByOwner () phương pháp.

5.2. ReactiveMongoRepository

Ngoài ra còn có ReactiveMongoRepository giao diện kế thừa từ ReactiveCrudRepository và thêm một số phương pháp truy vấn mới:

@Repository
public interface AccountReactiveRepository 
  extends ReactiveMongoRepository<Account, String> { }

Sử dụng ReactiveMongoRepository , chúng tôi có thể truy vấn bằng ví dụ:

Flux<Account> accountFlux = repository
  .findAll(Example.of(new Account(null, "owner", null)));

Do đó, chúng tôi sẽ nhận được mọi Tài khoản giống với ví dụ đã chuyển.

Với các kho lưu trữ của chúng tôi đã được tạo, chúng đã có các phương thức được xác định để thực hiện một số hoạt động cơ sở dữ liệu mà chúng tôi không cần phải thực hiện:

Mono<Account> accountMono 
  = repository.save(new Account(null, "owner", 12.3));
Mono<Account> accountMono2 = repository
  .findById("123456");

5.3. RxJava2CrudRepository

Với RxJava2CrudRepository, chúng tôi có cùng hoạt động với ReactiveCrudRepository, nhưng với kết quả và loại tham số từ RxJava :

@Repository
public interface AccountRxJavaRepository 
  extends RxJava2CrudRepository<Account, String> {
 
    Observable<Account> findAllByValue(Double value);
    Single<Account> findFirstByOwner(Single<String> owner);
}

5.4. Kiểm tra hoạt động cơ bản của chúng tôi

Để kiểm tra các phương pháp lưu trữ của chúng tôi, chúng tôi sẽ sử dụng người đăng ký thử nghiệm:

@Test
public void givenValue_whenFindAllByValue_thenFindAccount() {
    repository.save(new Account(null, "Bill", 12.3)).block();
    Flux<Account> accountFlux = repository.findAllByValue(12.3);

    StepVerifier
      .create(accountFlux)
      .assertNext(account -> {
          assertEquals("Bill", account.getOwner());
          assertEquals(Double.valueOf(12.3) , account.getValue());
          assertNotNull(account.getId());
      })
      .expectComplete()
      .verify();
}

@Test
public void givenOwner_whenFindFirstByOwner_thenFindAccount() {
    repository.save(new Account(null, "Bill", 12.3)).block();
    Mono<Account> accountMono = repository
      .findFirstByOwner(Mono.just("Bill"));

    StepVerifier
      .create(accountMono)
      .assertNext(account -> {
          assertEquals("Bill", account.getOwner());
          assertEquals(Double.valueOf(12.3) , account.getValue());
          assertNotNull(account.getId());
      })
      .expectComplete()
      .verify();
}

@Test
public void givenAccount_whenSave_thenSaveAccount() {
    Mono<Account> accountMono = repository.save(new Account(null, "Bill", 12.3));

    StepVerifier
      .create(accountMono)
      .assertNext(account -> assertNotNull(account.getId()))
      .expectComplete()
      .verify();
}

6. ReactiveMongoTemplate

Bên cạnh cách tiếp cận kho lưu trữ, chúng tôi có ReactiveMongoTemplate .

Trước hết, chúng ta cần đăng ký ReactiveMongoTemplate như một hạt đậu:

@Configuration
public class ReactiveMongoConfig {
 
    @Autowired
    MongoClient mongoClient;

    @Bean
    public ReactiveMongoTemplate reactiveMongoTemplate() {
        return new ReactiveMongoTemplate(mongoClient, "test");
    }
}

Và sau đó, chúng tôi có thể đưa bean này vào dịch vụ của mình để thực hiện các hoạt động cơ sở dữ liệu:

@Service
public class AccountTemplateOperations {
 
    @Autowired
    ReactiveMongoTemplate template;

    public Mono<Account> findById(String id) {
        return template.findById(id, Account.class);
    }
 
    public Flux<Account> findAll() {
        return template.findAll(Account.class);
    } 
    public Mono<Account> save(Mono<Account> account) {
        return template.save(account);
    }
}

ReactiveMongoTemplate cũng có một số phương pháp không liên quan đến miền mà chúng tôi có, bạn có thể xem chúng trong tài liệu.


  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Các toán tử mẫu MongoDB

  2. Kết nối với MongoDB qua SSL với Node.js

  3. Hiểu các tùy chọn sao lưu MongoDB

  4. MongoDB $ rtrim

  5. MongoDB Node findone làm thế nào để xử lý không có kết quả?