0

我正面临 vert.x 的问题。当触发超时时,它会生成一个响应,然后实际响应(需要 10 秒)来并尝试做出响应,所以我得到:

java.lang.IllegalStateException:响应已被写入

我是 Vert.x 的新手,我不确定所需的行为,我应该怎么做?,因为代码是异步的,我找不到检查响应是否已经发送的方法。

有没有办法正确地做到这一点?

我有这个代码:

private void setExternalCallAccessibleWithCircuitBreaker() {

        CircuitBreaker breaker = CircuitBreaker.create("my-circuit-breaker", vertx,
                new CircuitBreakerOptions().setMaxFailures(3) // number of failure before opening the circuit
                        .setTimeout(1000) // consider a failure if the operation does not succeed in time
                        .setFallbackOnFailure(true) // do we call the fallback on failure
                        .setResetTimeout(10000) // time spent in open state before attempting to re-try
        );

        vertx.createHttpServer().requestHandler(req -> {

            // some code executing with the breaker
            // the code reports failures or success on the given future.
            // if this future is marked as failed, the breaker increased the
            // number of failures
            breaker.executeWithFallback(future -> {

                // call the external service
                WebClient client = WebClient.create(vertx);

                client.get(8080, "localhost", "/wait10Seconds").send(ar -> {
                    if (ar.succeeded()) {

                        HttpResponse<Buffer> response = ar.result();

                        System.out.println("Received response with status code" + response.statusCode());
                        System.out.println("response.bodyAsString()" + response.bodyAsString());

                        req.response().end(response.body());
                        future.complete();

                    } else {
                        System.out.println("Something went wrong " + ar.cause().getMessage());
                        req.response().end("error");
                        future.fail("not possible to complete the request");
                    }
                });

            }, (Throwable exception) -> {

                req.response().end("error " + exception.getMessage());
                return exception;

            }).setHandler(ar -> {
                // Get the operation result.
                System.out.println("ar: " + ar);
            });

        }).listen(8088);
        System.out.println("Running");
    }
4

1 回答 1

3

我发现了这种方法,显然它有效:

if (!req.response().ended()) {
    req.response().end(response.body());
}
于 2020-01-27T16:42:46.437 回答