vertx.io에 대한 자습서를 여러 개 읽었지만 반복 코드를 최소화하는 방법을 여전히 이해할 수 없습니다.vertx에서 상용구 코드의 양을 줄이는 방법
예를 들어 DB에서 데이터를 가져 오는 RESTful 서비스를 구현해야합니다.
AdministratorService.java :
public void getAll(RoutingContext routingContext) {
jdbc.getConnection(ar -> {
SQLConnection connection = ar.result();
connection.query(Queries.SELECT_ALL_ADMINS, result -> {
List<Administrator> admins = result.result().getRows().stream().map(Administrator::new).collect(Collectors.toList());
routingContext.response()
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(admins));
connection.close();
});
});
}
public void getOneById(RoutingContext routingContext) {
final String id = routingContext.request().getParam("id");
if (id == null) {
routingContext.response().setStatusCode(400).end();
} else {
jdbc.getConnection(ar -> {
// Read the request's content and create an instance of Administrator.
SQLConnection connection = ar.result();
select(id, connection, Queries.SELECT_ONE_ADMIN_BY_ID, result -> {
if (result.succeeded()) {
routingContext.response()
.setStatusCode(200)
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(result.result()));
} else {
routingContext.response()
.setStatusCode(404).end();
}
connection.close();
});
});
}
}
CustomerService.java :
public void getAll(RoutingContext routingContext) {
jdbc.getConnection(ar -> {
SQLConnection connection = ar.result();
connection.query(Queries.SELECT_ALL_CUSTOMERS, result -> {
List<Customer> customers = result.result().getRows().stream().map(Customer::new).collect(Collectors.toList());
routingContext.response()
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(customers));
connection.close();
});
});
}
public void getOneById(RoutingContext routingContext) {
final String id = routingContext.request().getParam("id");
if (id == null) {
routingContext.response().setStatusCode(400).end();
} else {
jdbc.getConnection(ar -> {
// Read the request's content and create an instance of Administrator.
SQLConnection connection = ar.result();
select(id, connection, Queries.SELECT_ONE_CUSTOMER_BY_ID, result -> {
if (result.succeeded()) {
routingContext.response()
.setStatusCode(200)
.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(result.result()));
} else {
routingContext.response()
.setStatusCode(404).end();
}
connection.close();
});
});
}
}
하지 나는 테이블 (고객, 관리자) 및 구현 서비스 클래스에 대한이 개 빈 클래스를 준비했습니다 그 부분을보기가 어렵다.
.routingContext.response()
.putHeader("content-type", "application/json; charset=utf-8")
이 각 방법에서 반복됩니다. 일반적으로 이러한 클래스 간의 차이점은 SQL 요청과 Bean 클래스입니다.
예제를 공유하거나 방법을 변경하는 방법을 보여줄 수 있습니까?
주 (https://github.com/vert-x3/vertx-web 새로운 [콘텐츠 형식을 자동으로 설정하는 vertx - 웹 핸들러]있다/pull/524) – tsegismont