Vert.x初體驗

簡介

Vert.x項目起始於2011年,最開始的名字叫做 node.x,是一個仿照Node.js以Java開發的,基於EventLoop的異步非阻塞編程框架。Eclipse Vert.x是一個事件驅動的JVM上的框架,可以幫助我們構建現代、靈活、可擴展的程序。

使用Vert.x

1、新建maven項目,導入依賴

<dependencies>
    <dependency>
        <groupId>io.vertx</groupId>
        <artifactId>vertx-core</artifactId>
        <version>3.2.0</version>
    </dependency>
</dependencies>

2、編寫主函數

package com.qianyu;

import io.vertx.core.*;
import io.vertx.core.http.*;

public class Server {
    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        HttpServer httpServer = vertx.createHttpServer();
        httpServer.requestHandler(request -> request.response().end("hello, world"));
        httpServer.listen(8000);
    }
}

此時一個端口爲8000的http服務器已經開啓

3、在IDEA中編寫腳本測試

可以看到,返回字符串hello, world

GET http://localhost:8000

HTTP/1.1 200 OK
Content-Length: 12

hello, world

Response code: 200 (OK); Time: 277ms; Content length: 12 bytes

使用路由

1、導入web模塊

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

2、使用路由

package com.qianyu;

import io.vertx.core.*;
import io.vertx.core.http.*;
import io.vertx.ext.web.*;

public class Server {
    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        Router router = Router.router(vertx);
        router.get("/demo").blockingHandler(context -> {
            context.response().end("hello, world");
        });
        router.post("/demo").blockingHandler(context -> {
            context.response().end("this is post method");
        });
        HttpServer httpServer = vertx.createHttpServer();
        httpServer.requestHandler(router::accept);
        httpServer.listen(8000);
    }
}

3、使用IDEA編寫腳本測試

GET http://localhost:8000/demo

HTTP/1.1 200 OK
Content-Length: 12

hello, world

Response code: 200 (OK); Time: 19ms; Content length: 12 bytes
POST http://localhost:8000/demo

HTTP/1.1 200 OK
Content-Length: 19

this is post method

Response code: 200 (OK); Time: 122ms; Content length: 19 bytes
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章