【问题标题】:render http response in callback在回调中呈现 http 响应
【发布时间】:2019-10-25 18:29:21
【问题描述】:

我一直在阅读 Micronaut 文档,但我找不到在回调中呈现 http 响应的方法,因为我可以使用 Jax-Rs Jersey 来实现。

这是我想要实现的目标

@Get("/scalaFuture")
public void getScalaFuture() {
    Futures.successful(new SpringBootEntityDaoDTO())
            .onComplete(result -> {
                if (result.isSuccess()) {
                    return HttpResponse.ok(result.get());
                } else {
                    return HttpResponse.serverError(result.failed().get());
                }
            }, ExecutorContextUtil.defaultExecutionContext());
}

基本上在未来的回调中渲染响应。

类似于我在使用 AsyncResponse 的 Observable 回调中处理 JaxRS

@POST
@Path("/bla")
public void foo(@Suspended final AsyncResponse asyncResponse) {
    Observable<EntityDaoDTO> observable = observableFosConnectorManager.execute("EntityAggregateRoot", "database", getEntityDaoDTO(), null, MethodDTO.CREATE);
    observable
            .subscribeOn(Schedulers.computation())
            .subscribe(result -> {
                EntityPayLoad entityPayLoad = new EntityPayLoad();
                entityPayLoad.setTitle(result.getTitle());
                entityPayLoad.setDescription(result.getDescription());
                asyncResponse.resume(Response.status(Response.Status.OK.getStatusCode()).entity(entityPayLoad).build());
            }, t -> asyncResponse.resume(Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build()),
            () -> getLogger().info(null, "Subscription done"));
}

问候

【问题讨论】:

    标签: java java-8 micronaut


    【解决方案1】:

    Micronaut 允许不同的返回类型,包括响应式响应。

    例如,您可以返回CompletableFuture

    @Controller("/people")
    public class PersonController {
    
        Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();
    
        @Post("/saveFuture")
        public CompletableFuture<HttpResponse<Person>> save(@Body CompletableFuture<Person> person) {
            return person.thenApply(p -> {
                        inMemoryDatastore.put(p.getFirstName(), p);
                        return HttpResponse.created(p);
                    }
            );
        }
    
    }
    

    将您的 scala 未来转换为 Java 可完成的未来:https://stackoverflow.com/a/46695386/2534803

    https://docs.micronaut.io/latest/guide/index.html#_binding_using_completablefuture

    【讨论】:

    • 是的,我知道允许渲染 Rx2 和 Reactor 并评估发布者,但必须将 Future 转换为 CompletableFuture,即使一个简单的解决方案看起来很糟糕。我只是想知道为什么 Micronaut 没有像 JaxRs 那样呈现异步的功能
    • 因为现有的解决方案运行良好,不需要添加额外的方法来做同样的事情?
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 2016-08-15
    • 2014-10-20
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多