我在Spring Boot应用程序中运行Akka actor系统。我有一组演员在运行。
在我的Controller类中,我调用了我的服务类,该服务类使用Actor ask模式向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表示返回给客户机?模型?
发布于 2020-03-26 14:58:43
Future
、Mono
和CompletionStage
是同一概念的三个实现,这个值可能还存在,也可能不存在。您需要一种将它们转换为相同类型的方法,然后需要一种“扁平化”嵌套类型的方法。Mono.fromCompletionStage
就是这样一种方法,因为它将CompletionStage
转换为Mono
。
最简单的方法是完全避免获取Future
和扁平化:
在较新的Java版本(2.5.19或更高版本)中:存在ask
重载,使用java.time.Duration
超时,您将获得CompletionStage<SportEventDetail>
的返回值。还有ask
重载,它接受一个ActorSelection
,这样您就不必先解析,然后再询问解析完成的时间:
CompletionStage<SportEventDetail> futureSportEventDetails =
Patterns.ask(selection, message, Duration.ofSeconds(3))
return Mono.fromCompletionStage(futureSportEventDetails);
在较老版本的Akka (我认为是2.4.2及更高版本)中,您应该能够在akka.pattern.PatternsCS
中找到类似的签名。
如果您使用的是更老的版本,并且无法升级,则可能需要提供自己的从Future<T>
到CompletionStage<T>
或Mono<T>
的转换器方法,以便将来注册onComplete
侦听器并完成目标类型的实例。
https://stackoverflow.com/questions/60821756
复制