简体   繁体   English

如何从 Mono 获取用户 object<user> 没有在 Java 中阻止它?</user>

[英]How to get User object from Mono<User> without blocking it in Java?

I have a repository call which will give me Mono.我有一个存储库调用,它将给我 Mono。

ex:前任:

    private User getUserData (User user)
{
 Mono<User> monoUser=userRepository.insert(user);
  User user= monoUser.block; 
return user;
}

How to achieve this without blocking in spring reactive.如何在不阻塞 spring 反应的情况下实现这一点。 I don't want to do monoUser.block to get User object.我不想做 monoUser.block 来获取用户 object。

After getting userObject i need to convert id to UserId via Mapstruct.Also i want to achieve this without blocking so that i will be using reactive feature.获取 userObject 后,我需要通过 Mapstruct 将 id 转换为 UserId。我还想在不阻塞的情况下实现这一点,以便我将使用响应式功能。

There are a number of things you can do with a Mono instead of calling block , things that will not block.你可以用Mono做很多事情,而不是调用block ,这些事情不会阻止。 One thing you can do is attach a Consumer to it that gets called when the Mono 's action completes successfully.您可以做的一件事是将一个Consumer附加到它,当Mono的操作成功完成时,它会被调用。 The signature of the method to do that (on the Mono ) is:这样做的方法的签名(在Mono )是:

Mono<T> doOnSuccess(Consumer<? super T> onSuccess)

So then you can go on working, and your consumer will get called when the action completes.然后你可以继续工作,当动作完成时你的消费者会被调用。 That call would then initiate whatever actions you want to have performed after the user is added.然后,该调用将启动您希望在添加用户后执行的任何操作。

You put code in your Consumer that writes to the database.您将写入数据库的代码放在Consumer中。 If that object needs information, like a handle to the database to write to, you can hand it that information when you construct the object, before passing it in to the doOnSuccess call.如果该对象需要信息,例如要写入的数据库句柄,您可以在构造对象时将这些信息传递给doOnSuccess调用,然后再将其传递给doOnSuccess调用。 - ——

The correct way to handle this would be to link your Mono<> output with the function signature and consume it by calling the getUserData method in your Mono pipeline.处理此问题的正确方法是将 Mono<> output 与 function 签名链接,并通过在 Mono 管道中调用 getUserData 方法来使用它。 To consume it you'll have to maintain a complete reactive pipeline where all your operations are linked to one another through the various operations like map / flatmap.要使用它,您必须维护一个完整的反应式管道,其中所有操作通过 map / flatmap 等各种操作相互链接。 Alternatively if you just want to print the user inserted in your logs you can make use of.doOnNext() to print the same, this would run in a different thread which would not block your main Mono thread.或者,如果您只想打印插入日志中的用户,您可以使用.doOnNext() 来打印相同的内容,这将在不同的线程中运行,不会阻塞您的主 Mono 线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM