如何将返回 `void` 的同步方法包装成 Mono

huangapple go评论67阅读模式
英文:

How to wrap synchronous method that returns `void` into Mono<Void>?

问题

我正在尝试将 PostgreSQL 仓库的 deleteById 方法从返回 void 改为返回 Mono<Void>

该仓库是一个我自动注入的服务,我使用它的方式如下:

使用 String 类型的 id 作为参数调用 repository.deleteById(id)

英文:

I'm trying to adapt the postgresql repository deleteById method which return void to return Mono&lt;Void&gt;

the repository is a service that I autowired, I use it like this

repository.deleteById(id) with String id as the argument

答案1

得分: 2

如果您想使用响应式堆栈,则应使用spring-data-r2dbc,它提供了ReactiveCrudRepository和方法Mono<Void> deleteById(ID id)

如果由于某种原因需要使用同步方法,则可以使用Mono.fromRunnable来包装deleteById调用。

Mono.fromRunnable(() -> repository.deleteById(someId))

然而,应该避免这样做,因为这样您将无法从使用响应式堆栈中获得任何好处。

英文:

If you want to use reactive stack, then you should use spring-data-r2dbc, which provides ReactiveCrudRepository and method Mono&lt;Void&gt; deleteById(ID id).

If for some reason you need to use a synchronous method, then you could wrap deleteById call using Mono.fromRunnable

Mono.fromRunnable(() -&gt; repository.deleteById(someId))

However, this should be avoided, because then you get no benefits of using reactive stack.

huangapple
  • 本文由 发表于 2020年8月18日 19:05:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63467278.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定