如何从completableFuture创建Mono [英] How to create a Mono from a completableFuture
问题描述
我正在尝试将CompletableFuture
包装在Reactor Mono
类型中,以简化转换操作.总的来说,Project Reactor更方便!我正在使用AWS Lambda函数,并且正在使用新的AWS Java SDK 2.x版本调用诸如S3,SQS等的AWS服务.这个新的SDK允许对AWS服务进行异步调用,并返回CompleteableFuture对象.
I am trying to wrap CompletableFuture
inside a Reactor Mono
type in order to simplify my transform operations. Project Reactor is more convenient in general! I am working inside an AWS Lambda function and I am invoking AWS services such as S3, SQS, etc... using the new AWS Java SDK 2.x version. This new SDK allows to make asynchronous calls to AWS services and returns CompleteableFuture objects.
例如:
S3AsyncClient s3AsyncClient = S3AsyncClient.builder().build();
Mono.fromFuture(s3AsyncClient.getObject(b ->
b.bucket(bucketId).key(objectKey), AsyncResponseTransformer.toBytes()).subscribe()
System.out.println("stuff");
问题是,当我的主代码调用CompletableFuture
(s3AsyncClient.getObject)
时,执行线程突然切换到CompleteableFuture线程,而调用Mono的主方法在CompletableFuture完成之前返回.
The problem is, when my main code invokes the CompletableFuture
(s3AsyncClient.getObject)
, suddenly the execution thread switches to the CompleteableFuture thread and my main method that invoked the Mono returns before the CompletableFuture completes.
基本上,从上面的示例中可以看出,在s3AsyncClient.getObject
完成之前,将打印"stuff"
字符串.
Basically, from the example above, the "stuff"
string gets printed before the s3AsyncClient.getObject
completes.
如何确保Mono和CompletableFuture
在同一线程中执行,或者如何确保我的lambda在CompletableFuture
完成之前不会终止?
How can I make sure the Mono and the CompletableFuture
executes within the same thread or how do I make sure my lambda doesn't terminate before the CompletableFuture
have completed?
对于那些想知道的人,只有在将代码远程部署到AWS Lambda时才出现此行为.我在本地没有这种行为...
For those wondering, I only get this behavior when I deploy my code remotely to AWS Lambda. I don't experience this behavior locally...
推荐答案
//.thenApply will wait for your future to complete first and then return Mono<T>
Mono.fromFuture(yourCompletableFuture.thenApply(x -> x.doSomething);
//.thenApply will wait for your future to complete first and then return Mono<T>
Mono.fromFuture(yourCompletableFuture.thenApply(x -> x.doSomething);
这篇关于如何从completableFuture创建Mono的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!