【发布时间】:2020-07-04 09:36:03
【问题描述】:
我在 Spring Boot 应用程序中运行 Akka 演员系统。我有一组正在运行的 Actor。
从我的 Controller 类中,我调用我的服务类,使用 Actor 询问模式,向 Actor 发送消息并期望得到响应。下面是服务方法代码:
public Mono<Future<SportEventDetailed>> getEventBySportAndLeagueId(Integer sportId, Integer leagueId) {
final ActorSelection actorSelection = bootstrapAkka.getActorSystem().actorSelection("/user/some/path");
final ActorMessage message = new ActorMessage()
final CompletionStage<Future<SportEventDetails>> futureCompletionStage = actorSelection.resolveOne(Duration.ofSeconds(2))
.thenApplyAsync(actorRef ->
Patterns.ask(actorRef, message, 1000)
.map(v1 -> (SportEventDetails) v1, ExecutionContext.global())
)
.whenCompleteAsync((sportEventDetailsFuture, throwable) -> {
// Here sportEventDetailsFuture is of type scala.concurrent.Future
sportEventDetailsFuture.onComplete(v1 -> {
final SportEventDetails eventDetails = v1.get();
log.info("Thread: {} | v1.get - onComplete - SED: {}", Thread.currentThread(), eventDetails);
return eventDetails;
}, ExecutionContext.global());
});
return Mono.fromCompletionStage(futureCompletionStage);
}
虽然控制器代码很简单
@GetMapping(path = "{sportId}/{leagueId}")
public Mono<Future<SportEventDetails>> getEventsBySportAndLeagueId(@PathVariable("sportId") Integer sportId, @PathVariable("leagueId") Integer leagueId) {
return eventService.getEventBySportAndLeagueId(sportId, leagueId);
}
当客户端调用此端点时,它会得到{"success":true,"failure":false} 或null(作为字符串)。
我怀疑null 响应的问题是scala.concurrent.Future 在响应发送到客户端之前没有完成 - 但我不明白为什么它不能按时完成,因为我认为 Mono 会等待未来完成
这里的问题是Patterns.ask 返回一个scala.concurrent.Future<SportEventDetails>,我找不到将scala Future 转换为Java CompletableFuture<SportEventDetails> 或CompletionStage<SportEventDetails> 的方法。
所以,我的问题是:使用 Akka 的 Patterns.ask(...) 模型时,如何将 SportEventDetails 的 json 表示返回给客户端?
【问题讨论】:
标签: java spring scala akka reactor