Vert.x RESTful Verticle

4
我非常新于Vert.x,只有几天的经验。我来自JAX-RS、RESTeasy的世界。我可能非常错误,请指正。
所以,我想使用vertx-web和Spring编写REST API。我将Verticles视为REST资源。 我看了一下vertx-web blogspring-example,但这些示例非常简单,大多数只包含一个资源和Verticle。 我的问题是:如何使Verticle公开其自己的REST接口(子路由),并将其子路由注册到应用程序的主路由中?
我尝试了类似以下的内容,但当我请求/products/all时,我得到404错误:
public class ProductsVerticle extends AbstractVerticle {

@Override
public void start(Future<Void> startFuture) throws Exception {
    super.start(startFuture);
}

public static Router getRouter() {
    Router router = Router.router(Vertx.vertx());

    router.get("/all").consumes("application/json").produces("application/json")
            .handler(routingContext -> {
                routingContext.response()
                        .putHeader("content-type", "text/html")
                        .end("<h1>Products</h1>");
            });

    return router;
}

}

public class ServerVerticle extends AbstractVerticle {

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

    Router mainRouter = Router.router(vertx);
    ProductsVerticle productsVerticle = new ProductsVerticle();

    vertx.deployVerticle(productsVerticle, handler -> {
        if (handler.succeeded()) {
            LOG.info("Products Verticle deployed successfully");
            mainRouter.mountSubRouter("/products", productsVerticle.getRouter());
        }
    });

    mainRouter.get("/static").handler(routingContext -> {
        routingContext.response()
                .putHeader("content-type", "text/html")
                .end("<h1>Hello from my first Vert.x 3 application</h1>");
    });

    HttpServer server = vertx.createHttpServer();
    server.requestHandler(mainRouter::accept);
    server.listen(8090);
}

}

2个回答

2

您的需求是完全可以理解的。但我们可能需要简要思考一下Spring的作用:

当应用服务器启动时,会执行一个启动钩子(startuphook),该钩子会搜索整个类路径以查找所有使用Jax-rs注解的类,并对它们进行初始化或仅在“路由器”上注册。

因此,如果您想要这样做,您需要自己完成。非常抱歉:D。

例如:

class Server extends AbstractVerticle {

    @Override
    public void start() throws Exception {
        List<AbstractVerticle> verticles = searchForVerticlesWithMyAnnotation();
        verticles.forEach((V) = > router.add(V));
    }

}

@MyOwnJax(path = "/blaa")
public class TestService {
}

@interface MyOwnJax {
    String path();
}

这里的关键是方法“searchForVerticlesWIthMyAnnotation”。它不应该太慢。但如果您仍然使用Spring,您可以使用类似于以下内容的东西: org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider 或者看这里:Stackoverflow: Search for Annotations @runtime 但是这里有一个大问题。 ;) 也许您有比Spring更好的想法来创建REST API? 在我看来,Spring真的很笨重,而Vertx.x非常流畅。(对我的不太实用的意见感到抱歉。)
在我的应用程序中,我使用DI方法。这意味着:
router.route(HttpMethod.GET,
 "/user/login").handler(injector.getInstance(ILoginUser.class));

使用普通的Guice框架作为注入器。而这只是一个接口,您可以在必须更改启动服务器的垂直线之前进行真正的大更改。(实际上,主要是当您必须添加或删除路径时)
总结:
- 如果您想采用Spring方法,则必须使用反射或使用反射的库。 缺点:启动性能差,有时会出现过多的魔法和难以找到的错误/调试。 优点:非常易于测试,功能扩展非常容易。 - 自己在路径上注册垂直线。 缺点:您必须在“服务器”垂直线上添加/删除路径。 优点:启动性能好,没有魔法,完全控制发生的时间。
这只是一个简短的摘要,并没有提到许多要点。但我希望这回答了您的问题。如果您有后续问题,请写下来!

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接