Rest服务调用未触发处理程序



我正在用vert.x和Java编写一个应用程序。

我有一个课程,我已经注册了基本休息服务的终点:

private void setRoutes(Router router){
router.route("/*").handler(StaticHandler.create());
router.get("/service").handler(req -> {
getServices();//Call to Database and populate the services
List<JsonObject> jsonServices = services
.entrySet()
.stream()
.map(service ->
new JsonObject()
.put("name", service.getKey())
.put("status", service.getValue()))
.collect(Collectors.toList());
req.response().setStatusCode(200)
.putHeader("content-type", "application/json")
.end(new JsonArray(jsonServices).encode());
});
router.post("/service").handler(req -> {
JsonObject jsonBody = req.getBodyAsJson();
addService(jsonBody);//Persist the service
//services.put(jsonBody.getString("url"), "UNKNOWN");
req.response()
.putHeader("content-type", "text/plain")
.end("OK");
});

我正在对Get/服务端点进行HTTPGet调用,如下所示,我正在尝试获取响应状态代码。但每次线程都卡在conn.getResponseCode((上,然后什么也没发生。

此外,我的router.get("/service"(.handler从未被调用,在调试模式下,我可以看到ResponseCode的值为-1。从邮递员那里,当我点击这个网址时,我可以得到正确的结果,也可以从浏览器中得到适当的结果。为什么没有返回状态代码200。此外,它不会去接球或最后的盖帽。

private void checkService(String key,DBConnector connector) {


// TODO Auto-generated method stub
try {
URL url = new URL("http://localhost:8080/service");
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(50);
conn.connect();

if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//Update the status of the URL to OK
connector.query("UPDATE service set status = 'OK' where name = ?",new JsonArray().add(key)).setHandler(res -> {
if (res.succeeded()) {
System.out.println("Status updated to OK");
}

else {
//Handle this properly later
System.out.println("Failed to update the status to OK");

}
});
}
else {
connector.query("UPDATE service set status = 'FAIL' where name = ?",new JsonArray().add(key)).setHandler(res -> {
if (res.succeeded()) {
System.out.println("Status updated to fail");
}

else {
//Handle this properly later
System.out.println("Failed to update the status to fail");

}
});
}

} 
catch (Exception e) {
e.printStackTrace();
//Code to set the status to FAIL
connector.query("UPDATE service set status = 'FAIL' where name = ?",new JsonArray().add(key)).setHandler(res -> {
if (res.succeeded()) {
System.out.println("Status updated to fail");
}

else {
//Handle this properly later
System.out.println("Failed to update the status to fail");

}
});
}
finally {
System.out.println("INSIDE FINALLY");
}
System.out.println(" Done");
}

尝试在路由后设置静态处理程序:

router.get("/service").handler(req -> {...});
router.post("/service").handler(req -> {...});
router.route("/*").handler(StaticHandler.create());

Vertx路由器按照路由的连接顺序匹配路由。在当前状态下,所有与/*匹配的请求(包括/service(都会匹配并传递给静态处理程序。

https://vertx.io/docs/vertx-web/java/#_route_order

默认情况下,路由按照添加到路由器。

当请求到达时,路由器将遍历每条路由检查它是否匹配,如果匹配,则检查该路由的处理程序将被调用。

如果处理程序随后调用next,则下一个的处理程序将调用匹配的路由(如果有的话(。等等。

相关内容

  • 没有找到相关文章

最新更新