Vert.x を組み込み実行

Vert.x を Groovy と Java で組み込み実行してみました。

ソースは http://github.com/fits/try_samples/tree/master/blog/20130825/

Groovy で組み込み実行

まずは Groovy で組み込み実行してみます。

通常の Vert.x スクリプトとの違いは下記の通りです。

  • (1) Vertx オブジェクトを作成 (Groovy では Vertx.newVertx() を使用)
  • (2) プロセスを終了させないように待機処理が必要

下記では単純な HTTP サーバー処理を実装してみました。 (2) の用途に CountDownLatch を使ってますが、代わりに System.in.read() 等でもいいと思います。

embedded_vertx.groovy (Groovy版)
@Grab('io.vertx:vertx-core:2.0.1-final')
@Grab('io.vertx:lang-groovy:2.0.0-final')
import org.vertx.groovy.core.Vertx
import java.util.concurrent.CountDownLatch

// (1) Vertx オブジェクト作成
def vertx = Vertx.newVertx()

vertx.createHttpServer().requestHandler {req ->
    req.response.end 'test data'
}.listen 8080

println 'started ...'

// (2) 待機処理
def stopLatch = new CountDownLatch(1)

Runtime.runtime.addShutdownHook { ->
    println 'shutdown ...'
    stopLatch.countDown()
}

stopLatch.await()
実行例
> groovy embedded_vertx.groovy
started ...

Ctrl + c 等で終了します。

started ...
shutdown ...

Java で組み込み実行

Groovy 版との違いは以下の通りです。

  • VertxFactory.newVertx() で Vertx オブジェクトを作成

今回は Java SE 8 EA b102 を使って実行してみました。

EmbeddedVertx.javaJava SE 8 版)
package fits.sample;

import org.vertx.java.core.Vertx;
import org.vertx.java.core.VertxFactory;
import java.util.concurrent.CountDownLatch;

public class EmbeddedVertx {
    public static void main(String... args) throws Exception {
        // (1) Vertx オブジェクト作成
        Vertx vertx = VertxFactory.newVertx();

        vertx.createHttpServer().requestHandler( req ->
            req.response().end("test data")
        ).listen(8080);

        System.out.println("started ...");

        // (2) 待機処理
        waitStop();
    }

    private static void waitStop() {
        final CountDownLatch stopLatch = new CountDownLatch(1);

        Runtime.getRuntime().addShutdownHook(new Thread( () -> {
            System.out.println("shutdown ...");
            stopLatch.countDown();
        }));

        try {
            stopLatch.await();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

ビルドと実行には Gradle を使ってみました。

  • Gradle 1.7
build.gradle
apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    compile 'io.vertx:vertx-core:2.0.1-final'
}

task run(dependsOn: 'build') << {
    javaexec {
        main = 'fits.sample.EmbeddedVertx'
        classpath = runtimeClasspath
    }
}
実行例
> gradle run
・・・
:run
・・・
started ...
> Building > :run

なお、gradle で実行した場合、Ctrl + c で終了すると "shutdown ..." は出力されません。(java コマンドで実行した場合は出力されます)