Route order
在默认情况下routes的排序是按照添加添加进router的顺序进行排序的.
当router接受到一个请求时, router会遍历自身的每一个route查看是否与请求匹配,如果匹配的话,该route的handler就会被调用.
如果handler随后调用了下一个handler, 那么下一个与之匹配的route也会被调用.
Route route1 = router.route("/some/path/").handler(routingContext -> {HttpServerResponse response = routingContext.response();// enable chunked responses because we will be adding data as// we execute over other handlers. This is only required once and// only if several handlers do output.response.setChunked(true);response.write("route1\n");// Now call the next matching routeroutingContext.next();});Route route2 = router.route("/some/path/").handler(routingContext -> {HttpServerResponse response = routingContext.response();response.write("route2\n");// Now call the next matching routeroutingContext.next();});Route route3 = router.route("/some/path/").handler(routingContext -> {HttpServerResponse response = routingContext.response();response.write("route3");// Now end the responseroutingContext.response().end();});
在上面的例子中,输出结果为:
route1route2route3
/some/path开头的请求都是按照刚才的那个顺序进行route调用的.
如果你想要改变route的调用顺序,你可以使用order()方法,向其指定一个指定值.
Routes在router中的位置是按照他们添加进去的时间顺序进行排序的, 而且他们的位置是从0开始的.
当然像上文所说的,你还可以调用order()方法改变这个排序. 需要注意的是序号可以是负数, 例如你想要某个route在序号0的route之前执行,你就可以将某个route序号指定为-1.
下例中我们改变了route2的序号,确保他在route1之前执行.
Route route1 = router.route("/some/path/").handler(routingContext -> {HttpServerResponse response = routingContext.response();response.write("route1\n");// Now call the next matching routeroutingContext.next();});Route route2 = router.route("/some/path/").handler(routingContext -> {HttpServerResponse response = routingContext.response();// enable chunked responses because we will be adding data as// we execute over other handlers. This is only required once and// only if several handlers do output.response.setChunked(true);response.write("route2\n");// Now call the next matching routeroutingContext.next();});Route route3 = router.route("/some/path/").handler(routingContext -> {HttpServerResponse response = routingContext.response();response.write("route3");// Now end the responseroutingContext.response().end();});// Change the order of route2 so it runs before route1route2.order(-1);
接下来我们就看到了我们所期望的结果
route2route1route3
如果俩个route有相同的序号,那么他们会按照添加的顺序进行执行. 你还可以通过调用last()方法将某个route放到最后一个.
