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

huangapple 未分类评论44阅读模式
英文:

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");
}

请注意,上述代码中的&quot;被用于表示引号。如果您希望使用真实的引号,请将其替换为"

英文:

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

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(&quot;http://localhost:8080/service&quot;);
    System.out.println(url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(&quot;GET&quot;);
    conn.setConnectTimeout(50);
    conn.connect();

    
    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    	//Update the status of the URL to OK
    	connector.query(&quot;UPDATE service set status = &#39;OK&#39; where name = ?&quot;,new JsonArray().add(key)).setHandler(res -&gt; {
	        if (res.succeeded()) {
	           System.out.println(&quot;Status updated to OK&quot;);
	            }
	            
	         else {
	        	//Handle this properly later
	            System.out.println(&quot;Failed to update the status to OK&quot;);
	            
	        }
	    });
    }
    else {
    	connector.query(&quot;UPDATE service set status = &#39;FAIL&#39; where name = ?&quot;,new JsonArray().add(key)).setHandler(res -&gt; {
	        if (res.succeeded()) {
	           System.out.println(&quot;Status updated to fail&quot;);
	            }
	            
	         else {
	        	//Handle this properly later
	            System.out.println(&quot;Failed to update the status to fail&quot;);
	            
	        }
	    });
    }
    
} 
catch (Exception e) {
   e.printStackTrace();
    //Code to set the status to FAIL
   connector.query(&quot;UPDATE service set status = &#39;FAIL&#39; where name = ?&quot;,new JsonArray().add(key)).setHandler(res -&gt; {
        if (res.succeeded()) {
           System.out.println(&quot;Status updated to fail&quot;);
            }
            
         else {
        	//Handle this properly later
            System.out.println(&quot;Failed to update the status to fail&quot;);
            
        }
    });
}
finally {
	System.out.println(&quot;INSIDE FINALLY&quot;);
}

System.out.println(&quot; Done&quot;);

}

答案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(&quot;/service&quot;).handler(req -&gt; {...});

router.post(&quot;/service&quot;).handler(req -&gt; {...});

router.route(&quot;/*&quot;).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.

huangapple
  • 本文由 发表于 2020年7月25日 21:50:51
  • 转载请务必保留本文链接:https://java.coder-hub.com/63089159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定