You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Java与Vert.x开发REST API:是否需为各资源创建独立Verticle?

Should I create a separate Verticle for each REST resource in Vert.x?

Great question! Coming from Jersey to Vert.x, it’s totally normal to try mapping the patterns you already know to the new framework—and luckily, Vert.x gives you flexible options to align with your workflow. Let’s break down the two main approaches, their use cases, and how they compare to your Jersey experience:

1. Single Verticle with Route Groups (Most similar to Jersey)

This is the closest parallel to how you structured Jersey resources. Instead of creating a separate Verticle per resource, you’ll:

  • Create a single main Verticle that handles the HTTP server and root router.
  • Split each resource’s routing logic into dedicated classes (e.g., UsersRoutes, ProductsRoutes)—just like your UsersResource and ProductsResource classes in Jersey.
  • Each route class exposes a method to register its CRUD endpoints onto the root router.

This approach keeps things simple, especially if you’re new to Vert.x, and maintains the familiar separation of concerns from Jersey.

Example Code:

UsersRoutes.java (handles user-specific endpoints)

public class UsersRoutes {
    public static void setup(Router router) {
        // Inject or initialize your business logic service
        UsersService userService = new UsersService();

        // GET all users
        router.get("/users").handler(ctx -> {
            List<User> users = userService.getAllUsers();
            ctx.response()
               .putHeader("Content-Type", "application/json")
               .end(Json.encodePrettily(users));
        });

        // POST new user
        router.post("/users").handler(ctx -> {
            User newUser = ctx.getBodyAsJson().mapTo(User.class);
            userService.createUser(newUser);
            ctx.response().setStatusCode(201).end();
        });

        // Add PUT, DELETE endpoints here...
    }
}

Main API Verticle

public class MainApiVerticle extends AbstractVerticle {
    @Override
    public void start() {
        Router rootRouter = Router.router(vertx);

        // Mount route groups for each resource
        UsersRoutes.setup(rootRouter);
        ProductsRoutes.setup(rootRouter);

        // Start the HTTP server
        vertx.createHttpServer()
             .requestHandler(rootRouter)
             .listen(8080, result -> {
                 if (result.succeeded()) {
                     System.out.println("API server running on port 8080");
                 } else {
                     System.err.println("Failed to start server: " + result.cause());
                 }
             });
    }
}

2. Separate Verticle per Resource (For isolation/scalability)

If your resources have complex logic, need independent scaling, or you want fault isolation (so a bug in the products endpoint doesn’t take down the entire API), you can create a dedicated Verticle for each resource. Each Verticle manages its own sub-router, and you’ll integrate them into the main API server (either via direct mounting or the EventBus).

Key Benefits:

  • Isolation: Errors in one resource’s Verticle won’t crash the entire API.
  • Scalability: You can deploy multiple instances of high-traffic Verticles (e.g., UsersVerticle) to handle load, without scaling less busy resources.
  • Modularity: Teams can work on separate resources independently.

Example Code:

UsersVerticle.java

public class UsersVerticle extends AbstractVerticle {
    @Override
    public void start() {
        Router userRouter = Router.router(vertx);
        UsersService userService = new UsersService();

        // Define user endpoints relative to "/users"
        userRouter.get("/").handler(ctx -> {
            List<User> users = userService.getAllUsers();
            ctx.response()
               .putHeader("Content-Type", "application/json")
               .end(Json.encodePrettily(users));
        });

        userRouter.post("/").handler(ctx -> {
            User newUser = ctx.getBodyAsJson().mapTo(User.class);
            userService.createUser(newUser);
            ctx.response().setStatusCode(201).end();
        });

        // Register sub-router with main Verticle via EventBus
        vertx.eventBus().send("register-sub-router", new JsonObject()
           .put("prefix", "/users")
           .put("router", userRouter));
    }
}

Main API Verticle (integrates sub-routers)

public class MainApiVerticle extends AbstractVerticle {
    private Router rootRouter;

    @Override
    public void start() {
        rootRouter = Router.router(vertx);

        // Deploy resource Verticles
        vertx.deployVerticle(new UsersVerticle());
        vertx.deployVerticle(new ProductsVerticle());

        // Listen for sub-router registration events
        vertx.eventBus().consumer("register-sub-router", message -> {
            JsonObject payload = (JsonObject) message.body();
            String prefix = payload.getString("prefix");
            Router subRouter = payload.get("router");
            rootRouter.mountSubRouter(prefix, subRouter);
        });

        // Start HTTP server
        vertx.createHttpServer()
             .requestHandler(rootRouter)
             .listen(8080, result -> {
                 if (result.succeeded()) {
                     System.out.println("API server running on port 8080");
                 } else {
                     System.err.println("Failed to start server: " + result.cause());
                 }
             });
    }
}

Which Should You Choose?

  • Start with Route Groups: If you’re new to Vert.x, this approach feels most familiar (like Jersey) and keeps your codebase simple while you learn the framework.
  • Move to Separate Verticles: When your API grows, you need to scale specific resources independently, or you want better fault isolation.

Pro Tip (Regardless of Approach)

Just like in Jersey, always separate your routing logic from business logic. Use service classes (e.g., UsersService) to handle CRUD operations, data access, and business rules—this keeps your route handlers lean and your code easier to test and maintain.

内容的提问来源于stack exchange,提问作者Hleb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:42:22