问题
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.
For example:
S3AsyncClient s3AsyncClient = S3AsyncClient.builder().build();
Mono.fromFuture(s3AsyncClient.getObject(b ->
b.bucket(bucketId).key(objectKey), AsyncResponseTransformer.toBytes()).subscribe()
System.out.println("stuff");
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.
Basically, from the example above, the "stuff"
string gets printed before the s3AsyncClient.getObject
completes.
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?
For those wondering, I only get this behavior when I deploy my code remotely to AWS Lambda. I don't experience this behavior locally...
回答1:
//.thenApply will wait for your future to complete first and then return Mono<T>
Mono.fromFuture(yourCompletableFuture.thenApply(x -> x.doSomething);
来源:https://stackoverflow.com/questions/54154979/how-to-create-a-mono-from-a-completablefuture