2021年8月22日日曜日

Vert.x で MQTT クライアントを実装する

前提

  • OS: Windows 10 Pro
  • Java: openjdk version “11.0.2” 2019-01-15

MQTT プロジェクトのひな形を作成

Vert.x Starter - Create new Eclipse Vert.x applications を使用し、プロジェクトのひな形を作成する。

MQTT ブローカー起動

MQTT パブリッシャー・サブスクライバーの実装

MQTT | Eclipse Vert.x を参考に、自分で publish したトピックを自分で subscribe する MQTT クライアントを実装する。

1 秒周期で publish し、subscribe していることが確認できる。

実行ログ

PS C:\Users\mikoto\project\MiscellaneousStudy\java\Vertx\mqtt> ./mvnw compile exec:java
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< dev.mikoto2000.study.vertx:mqtt >-------------------
[INFO] Building mqtt 1.0.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mqtt ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\mikoto\project\MiscellaneousStudy\java\Vertx\mqtt\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ mqtt ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- exec-maven-plugin:3.0.0:java (default-cli) @ mqtt ---
8月 20, 2021 9:19:01 午前 io.vertx.core.impl.BlockedThreadChecker
警告: Thread Thread[vert.x-eventloop-thread-1,5,io.vertx.core.Launcher] has been blocked for 2348 ms, time limit is 2000 ms
8月 20, 2021 9:19:02 午前 io.vertx.mqtt.impl.MqttClientImpl
情報: Connection with localhost:1883 established successfully
connected localhost:1883.
{ topic: temperature, payload: 2021-08-20T09:19:03.505719800 }
{ topic: temperature, payload: 2021-08-20T09:19:04.506401500 }
{ topic: temperature, payload: 2021-08-20T09:19:05.506077900 }
{ topic: temperature, payload: 2021-08-20T09:19:06.505243 }
{ topic: temperature, payload: 2021-08-20T09:19:07.505362700 }
{ topic: temperature, payload: 2021-08-20T09:19:08.505559100 }
...(snip)

以上。

参考資料

Vert.x チュートリアルをやってみる

Get started | Eclipse Vert.x を試す。

前提

  • OS: Windows 11 Pro
  • Java: java version “1.8.0_201”
    • 諸事情あって Java8 です…

プロジェクトのひな形を作成

  1. Vert.x Starter - Create new Eclipse Vert.x applications にアクセスし、作成するアプリケーションの情報を入力し、 Generate Project ボタンを押下
    • Version: 4.1.2
    • Language: Java
    • Build: Maven
    • Group Id: dev.mikoto2000.study.vertex
    • Group Id: firststep
    • Dependencies:
      • Vert.x Web
  2. firststep.zip がダウンロードされるので、任意の場所に展開
  3. ソースとターゲットの変更
    • ダウンロードしたひな形は <release>11</release> と指定されているが、今回は Java8 を使うため、sourcetarget を指定する方法に修正する。以下コマンドを実行。
      • sed -i -e "s/<release>11<\/release>/<source>1.8<\/source>\\n <target>1.8<\/target>/" ./pom.xml

とりあえずテストを実行してみる

  1. ひな形プロジェクト展開したディレクトリへ移動
  2. コマンド ./mvnw.cmd clean test を実行

実行ログ

PS C:\Users\mikoto\project\MiscellaneousStudy\java\Vertx\firststep> ./mvnw clean test
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------< dev.mikoto2000.study.vertex:firststep >----------------
[INFO] Building firststep 1.0.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ firststep ---
[INFO] Deleting C:\Users\mikoto\project\MiscellaneousStudy\java\Vertx\firststep\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ firststep ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\mikoto\project\MiscellaneousStudy\java\Vertx\firststep\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ firststep ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\Users\mikoto\project\MiscellaneousStudy\java\Vertx\firststep\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ firststep ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\mikoto\project\MiscellaneousStudy\java\Vertx\firststep\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ firststep ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\Users\mikoto\project\MiscellaneousStudy\java\Vertx\firststep\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ firststep ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running dev.mikoto2000.study.vertex.firststep.TestMainVerticle
HTTP server started on port 8888
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.703 s - in dev.mikoto2000.study.vertex.firststep.TestMainVerticle
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.520 s
[INFO] Finished at: 2021-08-17T04:49:55+09:00
[INFO] ------------------------------------------------------------------------

ok.

ひな形のアプリケーション実行

  1. ひな形プロジェクト展開したディレクトリへ移動
  2. コマンド ./mvnw clean compile exec:java を実行
    • コンソールログに HTTP server started on port 8888
  3. ウェブブラウザで http://localhost:8888 へアクセス
    • ウェブブラウザに Hello from Vert.x! と表示される

ok.

アプリケーションを修正

package dev.mikoto2000.study.vertex.firststep;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;

public class MainVerticle extends AbstractVerticle {

  @Override
  public void start(Promise<Void> startPromise) throws Exception {
    // ルーター作成
    Router router = Router.router(vertx);

    // 全パスにマッチするルートを作成し、そこにハンドラを割り当てる
    // 全パスにマッチするルートなので、HTTP リクエストが来るたびにハンドラメソッドが実行される
    router.route().handler(context -> {
      // リクエスト送信元アドレスを取得
      String address = context.request().connection().remoteAddress().toString();

      // クエリーパラメーター `name` を取得
      MultiMap queryParams = context.queryParams();
      String name = queryParams.contains("name") ? queryParams.get("name") : "unknown";

      // JSON レスポンスを生成して返却するよう設定
      context.json(
        new JsonObject()
          .put("name", name)
          .put("address", address)
          .put("message", "Hello " + name + " connected from " + address)
      );
    });

    // HTTP サーバーを生成
    vertx.createHttpServer()
      // 上で作成したルーターを設定
      .requestHandler(router)
      // 待ち受けポート設定
      .listen(8888)
      // 待ち受けポートを標準出力へ
      .onSuccess(server ->
        System.out.println(
          "HTTP server started on port " + server.actualPort()
        )
      );
  }
}

修正したアプリの動作確認

./mvnw clean compile exec:java してからブラウザで localhost:8888?name=mikoto に接続。

パラメーターが反映されているのが確認できる。

今回はここまで。

参考資料