Vert.x -- 路由

Vert.x Router是核心组件,负责HTTP请求的路由处理。每个Route对应一个处理器,用于处理匹配的请求。可以设置正则匹配、指定HTTP方法及处理特定媒体类型的路由。通过示例代码展示如何配置和使用Router。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Router 是 Vert.x Web 的核心概念之一,它维护Route 的对象。

Router 接收 HTTP 请求,并查找首个匹配该请求的 Route,然后将请求传递给这个 Route。

Route 可以持有一个与之关联的处理器用于接收请求。可以通过处理器对请求进行操作,然后结束响应或者把请求传递给下一个匹配的处理器。

正则匹配路由:

Route route = router.route().pathRegex(".*foo");
Route route = router.routeWithRegex(".*foo");

指定 HTTP Method:

//匹配不止一个HTTP Method
Route route = router.route().method(HttpMethod.POST).method(HttpMethod.PUT);
router.get().handler(routingContext -> {
// 所有 GET 请求都会调用这个处理器
});

router.get("/some/path/").handler(routingContext -> {
// 所有路径为 `/some/path/` 的 GET 请求都会调用这个处理器
});

router.getWithRegex(".*foo").handler(routingContext -> {
// 所有路径以 `foo` 结尾的 GET 请求都会调用这个处理器
});

请求媒体类型路由:

router.route().consumes("text/html").consumes("text/plain").handler(routingContext -> {
// 所有 `content-type` 消息头的值为 `text/html` 或 `text/plain` 的请求会调用这个处理器
});

pom.xml

<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-core</artifactId>
    <version>3.5.4</version>
</dependency>
<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-web</artifactId>
    <version>3.5.4</version>
</dependency>

SimpleRouter.java

import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;

public class SimpleRouter extends AbstractVerticle {

  @Override
  public void start() throws Exception {

    HttpServer server = vertx.createHttpServer();
    //创建路由
    Router router = Router.router(vertx);
      //配置监听地址
      router.route(HttpMethod.GET,"/index")
        //使用 blockingHandler 方法来设置阻塞式处理器
        .blockingHandler(request -> {
          request.response().end("success");
        });

    //捕捉路径参数
    router.get("/method/:username/:password").handler(request ->{
      String username = request.request().getParam("username");
      String password = request.request().getParam("password");

      request.response()
        .putHeader("Content-type", "text/html;charset=utf-8")
        .end("用户名:" + username + " 密码:" + password);
    });

    router.get("/home").handler(new HomeHandle());


    Route route1 = router.route("/some/path/").handler(routingContext -> {
      HttpServerResponse response = routingContext.response();
      // 由于我们会在不同的处理器里写入响应,因此需要启用分块传输
      // 仅当需要通过多个处理器输出响应时才需要
      response.setChunked(true);
      response.write("route1\n");
      // 5 秒后调用下一个处理器
      routingContext.vertx().setTimer(5000, tid -> routingContext.next());
    });

    Route route2 = router.route("/some/path/").handler(routingContext -> {
      HttpServerResponse response = routingContext.response();
      response.write("route2\n");
      // 5 秒后调用下一个处理器
      routingContext.vertx().setTimer(5000, tid ->  routingContext.next());
    });

    Route route3 = router.route("/some/path/").handler(routingContext -> {
      HttpServerResponse response = routingContext.response();
      response.write("route3");
      // 结束响应
      routingContext.response().end();
    });

    //主路由
    Router mainRouter = Router.router(vertx);
    mainRouter.mountSubRouter("/main", router);

    //请求交由路由处理
    server.requestHandler(mainRouter::accept)
      .listen(8080);

  }

  @Override
  public void stop() throws Exception {
    super.stop();
  }
}

HomeHandle.java

import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;

public class HomeHandle implements Handler<RoutingContext> {

  @Override
  public void handle(RoutingContext routingContext) {
    routingContext.response().end("home");
  }
}

Main

import io.vertx.core.Vertx;

public class MainMethod {

  public static void main(String[] args) {
    SimpleRouter verticle = new SimpleRouter();

    Vertx vertx = Vertx.vertx();
    //部署verticle,调用start 方法
    vertx.deployVerticle(verticle);
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值