Vert.x实战一:Vert.x通过Http发布数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haoranhaoshi/article/details/89284847

WebService、Node.js、SpringBoot都能通过Http发布数据。Vert.x作为下一代异步、可伸缩、并发性企业级应用的服务器端框架,Http、TCP、WebSocket皆可发布。WebService、Node.js需先安装Tomcat等Web容器,SpringBoot内置Tomcat,Vert.x内置Vert.x容器。

package VertxHttpTest;

import java.io.IOException;
import java.util.function.Consumer;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;

// verticle是vert.x中的组件,一个组件可有多个实例,创建verticle都要继承AbstractVerticle
// 依赖vertx-web-3.7.0.jar、vertx-core-3.7.0.jar、slf4j-api-1.7.21.jar、slf4j-log4j12-1.7.5.jar、log4j.properties(src下),前两个必须,后三个推荐加入
public class VertxHttpTest extends AbstractVerticle {

    public static void main(String[] args) throws IOException {
        String verticleID = VertxHttpTest.class.getName();
        runExample(verticleID);
    }

    @Override
    public void start() throws Exception {

        final Router router = Router.router(vertx);

        router.route().handler(BodyHandler.create());
        // router.get("/hello")表示所监听URL路径
        router.get("/hello").handler(new Handler<RoutingContext>() {

            public void handle(RoutingContext event) {
                event.response().putHeader("content-type", "text/html").end("Hello Vert.x");
            }
        });
        // 传递方法引用,监听端口
        vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() {

            public void handle(HttpServerRequest event) {
                router.accept(event);
            }
        }).listen(33322);// 监听端口号
        // 访问http://localhost:33322/hello可查看结果
    }

    public static void runExample(String verticleID) {
        VertxOptions options = new VertxOptions();

        Consumer<Vertx> runner = vertx -> {
            vertx.deployVerticle(verticleID);
        };
        // Vert.x实例是vert.x api的入口点,我们调用vert.x中的核心服务时,均要先获取vert.x实例,
        // 通过该实例来调用相应的服务,例如部署verticle、创建http server
        Vertx vertx = Vertx.vertx(options);
        runner.accept(vertx);
    }
}

猜你喜欢

转载自blog.csdn.net/haoranhaoshi/article/details/89284847