ReactiveMongoRepository 不保存我的数据

ReactiveMongoRepository not saving my data

我是 springmongo 以及 noSQL 的菜鸟。

我已经在本地连接到我的 mongoDB。

然而,我试图拯救我的实体却一直失败。

val a0 = myEntity(name = "my Entity")
repository.save(a0)

我的存储库扩展 ReactiveMongoRepository<MyEntity, Long>.

但是当我将其更改为扩展 MongoRepository<MyEntity, Long> 时,它就起作用了。

可能是什么问题?

我的数据库实例 运行 并且工作正常。 我猜它必须对反应性事物做一些事情。

如果你使用反应流,你应该知道 nothing happens until you subscribe:

In Reactor, when you write a Publisher chain, data does not start pumping into it by default. Instead, you create an abstract description of your asynchronous process (which can help with reusability and composition).

By the act of subscribing, you tie the Publisher to a Subscriber, which triggers the flow of data in the whole chain. This is achieved internally by a single request signal from the Subscriber that is propagated upstream, all the way back to the source Publisher.

这意味着如果您使用 ReactiveMongoRepository,则您必须沿线某处订阅您的反应流。这可以通过在任何 Publisher 上使用 subscribe() 方法来完成。例如,使用 Java,即:

reactiveRepository
    .save(myEntity)
    .subscribe(result => log.info("Entity has been saved: {}", result));

此外,如果您编写响应式控制器,Webflux 等框架将为您处理订阅。使用 Java 意味着你可以这样写:

@GetMapping
public Mono<MyEntity> save() {
    return reactiveRepository.save(myEntity); // subscribe() is done by the Webflux framework
}

显然,反应式编程远不止于此,您应该意识到,如果不适应反应式生态系统和使用反应式编程,就不能简单地将 MongoRepository 换成 ReactiveMongoRepository

Reactor 参考指南中有一个 Introduction to Reactive Programming 章节值得一读。前面引用的文档也来自参考指南的这一章。

让您使用 subscribe() 操作流式传输终端并同时获得 Mono 结果 - 分成两个单独的操作:

val a0 = myEntity(name = "my Entity");
Mono<?> savedEntity = repository.save(a0);
savedEntity.subscribe();
return savedEntity;