Vert.xを使用したブラウザからの入力からバックエンド処理までの基本サンプル

Vert.xは高いパフォーマンスゆえに徐々に人気が高まっています。以下ではVert.xの入門サンプルを紹介します。

依存関係の追加

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

1. URLをインターセプトするVerticleの作成

package sample.vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

public class WebVerticle extends AbstractVerticle {

    @Override
    public void start() {
        Router router = Router.router(vertx);
        router.route().handler(BodyHandler.create());

        router.route("/process").handler(ctx -> {
            // リクエストパラメータの取得
            String username = ctx.request().getParam("username");
            String password = ctx.request().getParam("password");

            // JsonObjectにパラメータを格納
            JsonObject requestBody = new JsonObject()
                .put("username", username)
                .put("password", password);

            // イベントバス経由でサービスに送信
            vertx.eventBus().<JsonObject>request(
                ServiceVerticle.SERVICE_ADDRESS,
                requestBody,
                reply -> {
                    if (reply.succeeded()) {
                        JsonObject responseBody = reply.result().body();
                        // JSONP形式でレスポンス(実際のケースでは適切な形式に変更)
                        ctx.response()
                            .putHeader("content-type", "application/javascript")
                            .end("callback(" + responseBody.encode() + ")");
                    } else {
                        ctx.response()
                            .setStatusCode(500)
                            .end(reply.cause().getMessage());
                    }
                }
            );
        });

        vertx.createHttpServer()
            .requestHandler(router)
            .listen(8080);
    }
}

2. イベント処理用Verticleの作成

package sample.vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;

public class ServiceVerticle extends AbstractVerticle {

    public static final String SERVICE_ADDRESS = "SERVICE_ADDRESS";

    @Override
    public void start() {
        vertx.eventBus().consumer(SERVICE_ADDRESS, msg -> {
            // メッセージの受信と処理
            JsonObject received = (JsonObject) msg.body();
            System.out.println("Received: " + received.encodePrettily());

            // 実際のビジネスロジックはここに記述
            // 今回は受信データをそのまま返す
            msg.reply(received);
        });
    }
}

3. メインVerticleの作成(複数のVerticleをデプロイ)

package sample.vertx;

import io.vertx.core.Vertx;

public class MainVerticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(new ServiceVerticle());
        vertx.deployVerticle(new WebVerticle());
    }
}

4. ブラウザからアクセス

URL: http://localhost:8080/process?username=test&password=secret

ブラウザに表示される内容(JSONP形式の例):

callback({"username":"test","password":"secret"})

タグ: Vert.x Java REST API EventBus JSONP

7月17日 02:23 投稿