1
我已閱讀了vertx.io上的幾個教程,但我仍無法理解如何最小化重複代碼。如何減少vert.x中樣板代碼的數量
例如,我需要實現從數據庫獲取數據的RESTful服務。我已經準備了2種bean類的表格(客戶,管理員)和實施服務類:
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類。
你可以分享你的例子或者展示如何改變我的方法嗎?
注意,在3.4(於本週公佈),有一個新的[vertx的web處理程序來設置內容類型自動(https://github.com/vert-x3/vertx-web /拉/ 524) – tsegismont