LoginSignup
4
2

More than 5 years have passed since last update.

kotlinによるvert.xラッパー(vertx3-lang-kotlin)を更にラップしてみるYO!

Last updated at Posted at 2015-12-25

Kotlinのウェブフレームワークを探しているのですが、vertx3-lang-kotlinがなかなか良さそうです。
Vert.xのラッパーのようなので安定性やパフォーマンス面でも問題ないでしょう。

vertx3-lang-kotlinによるHTTP処理

import io.vertx.kotlin.lang.*

fun main(args: Array<String>) {
    DefaultVertx {
        httpServer(8084, "0.0.0.0", Route {
            GET("/path") { request ->
                bodyJson {
                    "field1" to "test me not"
                }
            }

            otherwise {
                setStatus(404, "Resource not found")
                body {
                    write("The requested resource was not found\n")
                }
            }
        })
    }
}

簡潔ですしなかなかよいのですが、ルーター周りが分割もできなさそうだしあまり好みではない感じです。(主観)
僕は一般的なMVCフレームワークみたいに、コントローラクラスがルーター的な定義をあるていど内包する形式が好みです。

そこで、vertx3-lang-kotlinを更にラップして好みな感じにしてみました。
(vertxのオブジェクトも露出する前提なので、ラップしたというよりルーター部分を取り替えたという方が近いかも)
そのラップしたフレームワークを使ってコントローラの定義とサービスの実行などをする例がこちら。

package net.devneko.birdx

import io.vertx.core.Vertx
import io.vertx.kotlin.lang.json.object_

class MyController(handler: RequestHandler) : RequestHandler by handler {

    companion object Router {
        fun new(v:RequestHandler) = MyController(v)
        fun router() = BirdxRouter.new {
            get("/controller", { new(this).index() })
        }
    }

    fun index() {
        replyText("controller index")
    }
}

class MyAppService(val vertx:Vertx) {
    fun execute(param:String, resultHandler:(String)->Unit) {
        // 時間のかかる処理を非同期で実行
        vertx.executeBlocking<String>({ h ->
            Thread.sleep(1000);
            val result = param + param
            h.complete(result)
        },{ asyncResult ->
            // 結果をコントローラに返す
            resultHandler(asyncResult.result())
        })
    }
}

fun main(args : Array<String>) {

    val birdx = Birdx {
        router {
            get("/") {
                // パラメータを渡してサービスを実行
                MyAppService(vertx).execute(param("msg")) { result ->
                    replyText(result)
                }
            }
        }
    }

    // コントローラを追加できる
    val r1 = BirdxRouter()
    r1.get("/add",{
        replyJson {
            object_("a" to "b")
        }
    })
    birdx.addRouter(r1)

    // よくあるコントローラクラスみたいのも使える
    birdx.addRouter(MyController.router())

    // サーバー起動
    birdx.start(8080)
}

すっきりしない部分はあるものの、ルーター・コントローラー周りは分割しやすくなりました。

それにしてもKotlin,Vert.xの組み合わせはなかなか可能性を感じますので、これで小さなサービスでも作ってみたいですね。

一応GitHubにおいておきます。

GitHub:dotneet/birdx

来年はKotlin飛躍の年となりますように。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2