英文:
Rest service call is not triggering the handler
问题
我正在使用Vert.x和Java编写一个应用程序。
我有一个类,在其中注册了基本REST服务的端点:
private void setRoutes(Router router) {
router.route("/*").handler(StaticHandler.create());
router.get("/service").handler(req -> {
getServices(); // 调用数据库并填充服务
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); // 持久化服务
// services.put(jsonBody.getString("url"), "UNKNOWN");
req.response()
.putHeader("content-type", "text/plain")
.end("OK");
});
}
我正在使用以下方式进行HTTP Get调用到GET /service端点,并尝试获取响应状态码。但是每次线程都会在conn.getResponseCode()
处卡住,然后什么都不发生。
而且,我的router.get("/service").handler
从未被调用,在调试模式下,我可以看到ResponseCode
的值为-1。从Postman中访问此URL时,我能够获得正确的结果,从浏览器中也可以获得正确的结果。为什么不返回状态码200?也不会进入catch或finally块。
private void checkService(String key, DBConnector connector) {
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) {
// 更新URL的状态为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 {
// 稍后正确处理
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 {
// 稍后正确处理
System.out.println("Failed to update the status to fail");
}
});
}
} catch (Exception e) {
e.printStackTrace();
// 设置状态为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 {
// 稍后正确处理
System.out.println("Failed to update the status to fail");
}
});
} finally {
System.out.println("INSIDE FINALLY");
}
System.out.println("Done");
}
请注意,上述代码中的"
被用于表示引号。如果您希望使用真实的引号,请将其替换为"
。
英文:
I am writing an application in vert.x and Java.
I have a class in which I have registered the end points for basic rest services:
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");
});
I am making a HTTP Get call to the GET /service end point as shown below and I am trying to get the response status code. But every-time the thread just gets stuck at the conn.getResponseCode() and then nothing happens.
Also my router.get("/service").handler is never called and in debug mode I can see that ResponseCode has a value of -1. From postman when I hit this url I am able to get proper results and also from the browser I can get proper results. Why is status code 200 not being returned. Also it does not go the catch or the finally blocks.
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");
}
答案1
得分: 0
尝试在您的路由之后设置静态处理程序:
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,则会调用下一个匹配路由的处理程序(如果有)。依此类推。
英文:
Try setting the static handler after your routes:
router.get("/service").handler(req -> {...});
router.post("/service").handler(req -> {...});
router.route("/*").handler(StaticHandler.create());
Vertx routers match routes in the order they were attached in. In your current state all requests matching /*
which would include /service
are matched and passed to the static handler.
https://vertx.io/docs/vertx-web/java/#_route_order
> By default routes are matched in the order they are added to the
> router.
>
> When a request arrives the router will step through each route and
> check if it matches, if it matches then the handler for that route
> will be called.
>
> If the handler subsequently calls next the handler for the next
> matching route (if any) will be called. And so on.
专注分享java语言的经验与见解,让所有开发者获益!
评论