Route order

在默认情况下routes的排序是按照添加添加进router的顺序进行排序的.

router接受到一个请求时, router会遍历自身的每一个route查看是否与请求匹配,如果匹配的话,该route的handler就会被调用.

如果handler随后调用了下一个handler, 那么下一个与之匹配的route也会被调用.

  1. Route route1 = router.route("/some/path/").handler(routingContext -> {
  2. HttpServerResponse response = routingContext.response();
  3. // enable chunked responses because we will be adding data as
  4. // we execute over other handlers. This is only required once and
  5. // only if several handlers do output.
  6. response.setChunked(true);
  7. response.write("route1\n");
  8. // Now call the next matching route
  9. routingContext.next();
  10. });
  11. Route route2 = router.route("/some/path/").handler(routingContext -> {
  12. HttpServerResponse response = routingContext.response();
  13. response.write("route2\n");
  14. // Now call the next matching route
  15. routingContext.next();
  16. });
  17. Route route3 = router.route("/some/path/").handler(routingContext -> {
  18. HttpServerResponse response = routingContext.response();
  19. response.write("route3");
  20. // Now end the response
  21. routingContext.response().end();
  22. });

在上面的例子中,输出结果为:

  1. route1
  2. route2
  3. route3

/some/path开头的请求都是按照刚才的那个顺序进行route调用的.

如果你想要改变route的调用顺序,你可以使用order()方法,向其指定一个指定值.

Routesrouter中的位置是按照他们添加进去的时间顺序进行排序的, 而且他们的位置是从0开始的.

当然像上文所说的,你还可以调用order()方法改变这个排序. 需要注意的是序号可以是负数, 例如你想要某个route在序号0的route之前执行,你就可以将某个route序号指定为-1.

下例中我们改变了route2的序号,确保他在route1之前执行.

  1. Route route1 = router.route("/some/path/").handler(routingContext -> {
  2. HttpServerResponse response = routingContext.response();
  3. response.write("route1\n");
  4. // Now call the next matching route
  5. routingContext.next();
  6. });
  7. Route route2 = router.route("/some/path/").handler(routingContext -> {
  8. HttpServerResponse response = routingContext.response();
  9. // enable chunked responses because we will be adding data as
  10. // we execute over other handlers. This is only required once and
  11. // only if several handlers do output.
  12. response.setChunked(true);
  13. response.write("route2\n");
  14. // Now call the next matching route
  15. routingContext.next();
  16. });
  17. Route route3 = router.route("/some/path/").handler(routingContext -> {
  18. HttpServerResponse response = routingContext.response();
  19. response.write("route3");
  20. // Now end the response
  21. routingContext.response().end();
  22. });
  23. // Change the order of route2 so it runs before route1
  24. route2.order(-1);

接下来我们就看到了我们所期望的结果

  1. route2
  2. route1
  3. route3

如果俩个route有相同的序号,那么他们会按照添加的顺序进行执行. 你还可以通过调用last()方法将某个route放到最后一个.