java Vert.x 3 OpenAPI 3支持
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Vert.x 3 OpenAPI 3支持相关的知识,希望对你有一定的参考价值。
package demo.microshop.rx.api;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RequestParameters;
import io.vertx.ext.web.validation.ValidationException;
import io.vertx.rxjava.core.AbstractVerticle;
import io.vertx.rxjava.ext.web.Router;
import io.vertx.rxjava.ext.web.RoutingContext;
import io.vertx.rxjava.ext.web.designdriven.openapi3.OpenAPI3RouterFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ApiVerticle extends AbstractVerticle {
private static final String API_SPEC_URL = "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore-expanded.yaml";
private static final Logger LOG = LoggerFactory.getLogger(ApiVerticle.class);
@Override
public void start(Future<Void> future) throws Exception {
OpenAPI3RouterFactory
.rxCreateRouterFactoryFromURL(vertx, API_SPEC_URL, false)
.subscribe(routerFactory -> {
// configure routes
routerFactory
.addHandlerByOperationId("findPets", this::findPets)
.addHandlerByOperationId("find pet by id", this::findPetById)
.setValidationFailureHandler(this::handleValidationFailure)
.getDelegate()
.enableValidationFailureHandler(true);
// construct router
Router router = routerFactory.getRouter();
// start HTTP server
vertx.createHttpServer()
.requestHandler(router::accept)
.rxListen(config().getInteger("server.port", 8989))
.subscribe(
server -> {
LOG.info("HTTP server listening on port {}", server.actualPort());
future.complete();
},
failure -> {
LOG.error(failure.getMessage(), failure);
future.fail(failure);
}
);
}, error -> LOG.error(error.getMessage(), error.getCause()));
}
/**
*
* @param routingContext
*/
public void findPets(RoutingContext routingContext) {
routingContext
.response()
.setStatusCode(200)
.putHeader("Content-Type", "application/json")
.end("{}");
}
/**
*
* @param routingContext
*/
private void findPetById(RoutingContext routingContext) {
RequestParameters params = routingContext.get("parsedParameters");
long id = params.pathParameter("id").getLong();
routingContext
.response()
.setStatusCode(200)
.putHeader("Content-Type", "application/json")
.end(new JsonObject().put("id", id).encodePrettily());
}
private void handleValidationFailure(RoutingContext routingContext) {
Throwable failure = routingContext.failure();
if (failure instanceof ValidationException) {
JsonObject response = toErrorResponse((ValidationException) failure);
routingContext
.response()
.setStatusCode(400)
.setStatusMessage("Validation Error")
.end(response.encodePrettily());
}
}
private static JsonObject toErrorResponse(ValidationException failure) {
return new JsonObject()
.put("status", 400)
.put("message", failure.getMessage())
.put("parameterName", failure.parameterName())
.put("value", failure.value());
}
}
以上是关于java Vert.x 3 OpenAPI 3支持的主要内容,如果未能解决你的问题,请参考以下文章