Kotlin框架巡禮

首先要說明,Kotlin支持你所知道的全部Java框架和庫,包括但不限於Spring全家桶、Guice、Hibernate、MyBatis、Jackson等,甚至有人在用Kotlin寫Spark大數據程序,所以Kotlin不須要專門的框架。所以,爲Kotlin開發框架的人,都是懷着滿滿的愛!java

Kotlin如今主要流行於Android開發,我是搞後端開發的,不熟悉Android,就不妄言了。這篇文章主要介紹後端框架,包括Web、SQL、依賴注入、測試這些方面。git

Web框架

Wasabi

- An HTTP Framework https://github.com/wasabifx/wasabigithub

極簡的Web框架,基於Netty構建,編程風格效仿了Ruby的Sinatra和Node.js的Express。web

Java也有個效仿Sinatra風格的Web框架,叫Spark(是的,與某大數據框架重名了)。sql

使用很簡單:編程

var server = AppServer()

server.get("/", { response.send("Hello World!") })

server.start()

也能夠這麼寫:json

server.get(「/「) { response.send("Hello World!") }

加一個前置攔截器(next()表示進入下一步處理):後端

server.get("/",
    {
      val log = Log()

      log.info("URI requested is ${request.uri}")
      next()
    },
    {
      response.send("Hello World!", "application/json")
    }
  )

獲取參數:安全

server.get("/customer/:id", { val customerId = request.routeParams["id"] } )
server.get("/customer", { val customerName = request.queryParams["name"] } )

爲了提供可維護性,能夠在別處定義一個方法,在程序入口引用它:app

appServer.get("/customer", ::getCustomer)

這種微框架很適合快速爲一個後端服務添加REST接口

Kara

https://github.com/TinyMissio...

JetBrains官方支持的Web框架,特點是類型安全的HTML DSL和CSS DSL (風格相似Haml/Slim和SASS/LESS)

由於Kotlin是支持動態執行代碼的,因此DSL理論上是能夠熱修改的,可是不知道Kara框架有沒有內置這個特性。

DSL示例

HTML View:

class Index() : HtmlView() {
    override fun render(context: ActionContext) {
        h2("Welcome to Kara")
        p("Your app is up and running, now it's time to make something!")
        p("Start by editing this file here: src/com/karaexample/views/home/Index.kt")
    }
}

HTML Layout:

class DefaultLayout() : HtmlLayout() {
    override fun render(context: ActionContext, mainView: HtmlView) {
        head {
            title("Kara Demo Title")
            stylesheet(DefaultStyles())
        }
        body {
            h1("Kara Demo Site")
            div(id="main") {
                renderView(context, mainView)
            }
            a(text="Kara is developed by Tiny Mission", href="http://tinymission.com")
        }
    }
}

Forms:

class BookForm(val book : Book) : HtmlView() {
  override fun render(context: ActionContext) {
    h2("Book Form")
    formFor(book, "/updatebook", FormMethod.Post) {
      p {
        labelFor("title")
        textFieldFor("title")
      }
      p {
        labelFor("isPublished", "Is Published?")               
        checkBoxFor("isPublished")
      }
    }
  }
}

CSS:

class DefaultStyles() : Stylesheet() {
    override fun render() {
        s("body") {
            backgroundColor = c("#f0f0f0")
        }
        s("#main") {
            width = 85.percent
            backgroundColor = c("#fff")
            margin = box(0.px, auto)
            padding = box(1.em)
            border = "1px solid #ccc"
            borderRadius = 5.px
        }
    
        s("input[type=text], textarea") {
            padding = box(4.px)
            width = 300.px
        }
        s("textarea") {
            height = 80.px
        }
    
        s("table.fields") {
            s("td") {
                padding = box(6.px, 3.px)
            }
            s("td.label") {
                textAlign = TextAlign.right
            }
            s("td.label.top") {
                verticalAlign = VerticalAlign.top
            }
        }
    }
}

其實就是在寫Kotlin代碼,顯然你能夠自行擴展出更多的DSL,還能夠用面向對象或函數式的方式來複用。

Controllers 像Spring MVC和Django的風格

不須要用到反射,性能更高:

object Home {
    val layout = DefaultLayout()

    Get("/")
    class Index() : Request({
        karademo.views.home.Index()
    })
    
    Get("/test")
    class Test() : Request({
        TextResult("This is a test action, yo")
    })
    
    Post("/updatebook")
    class Update() : Request({
        redirect("/forms")
    })
    
    Get("/complex/*/list/:id")
    Complex(id : Int) : Request({
        TextResult("complex: ${params[0]} id = ${params["id"]}")
    })
}

固然也有攔截器,在這裏叫Middleware

實現這個接口並綁定到路由路徑就能夠了:

/**
*    Base class for Kara middleware.
*    Middleware is code that is injected inside the request pipeline,
*    either before or after a request is handled by the application.
      */
     abstract class Middleware() {

      /**
     * Gets called before the application is allowed to handle the request.
     * Return false to stop the request pipeline from executing anything else.
       */
    abstract fun beforeRequest(context : ActionContext) : Boolean

    /**
     * Gets called after the application is allowed to handle the request.
     * Return false to stop the request pipeline from executing anything else.
     */
    abstract fun afterRequest(context : ActionContext) : Boolean

}
appConfig.middleware.add(MyMiddleware(), "/books")

綜合來講,Kara確實是比較優秀的web框架。

但有一點很差,默認使用3000端口,與Rails重複了。

SQL框架

Exposed

https://github.com/jetbrains/...

JetBrains官方支持的SQL/ORM框架,風格頗爲相似Django ORM,而且充分發揮了Kotlin的強類型優點。

項目主頁有很長一段示例代碼,全程都是強類型,很是流暢,使人賞心悅目:

import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.SchemaUtils.create
import org.jetbrains.exposed.sql.SchemaUtils.drop

object Users : Table() {
    val id = varchar("id", 10).primaryKey() // Column<String>
    val name = varchar("name", length = 50) // Column<String>
    val cityId = (integer("city_id") references Cities.id).nullable() // Column<Int?>
}

object Cities : Table() {
    val id = integer("id").autoIncrement().primaryKey() // Column<Int>
    val name = varchar("name", 50) // Column<String>
}

fun main(args: Array<String>) {
    Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")

    transaction {
        create (Cities, Users)

        val saintPetersburgId = Cities.insert {
            it[name] = "St. Petersburg"
        } get Cities.id

        val munichId = Cities.insert {
            it[name] = "Munich"
        } get Cities.id

        Cities.insert {
            it[name] = "Prague"
        }

        Users.insert {
            it[id] = "andrey"
            it[name] = "Andrey"
            it[cityId] = saintPetersburgId
        }

        Users.insert {
            it[id] = "sergey"
            it[name] = "Sergey"
            it[cityId] = munichId
        }

        Users.insert {
            it[id] = "eugene"
            it[name] = "Eugene"
            it[cityId] = munichId
        }

        Users.insert {
            it[id] = "alex"
            it[name] = "Alex"
            it[cityId] = null
        }

        Users.insert {
            it[id] = "smth"
            it[name] = "Something"
            it[cityId] = null
        }

        Users.update({Users.id eq "alex"}) {
            it[name] = "Alexey"
        }

        Users.deleteWhere{Users.name like "%thing"}

        println("All cities:")

        for (city in Cities.selectAll()) {
            println("${city[Cities.id]}: ${city[Cities.name]}")
        }

        println("Manual join:")
        (Users innerJoin Cities).slice(Users.name, Cities.name).
            select {(Users.id.eq("andrey") or Users.name.eq("Sergey")) and
                    Users.id.eq("sergey") and Users.cityId.eq(Cities.id)}.forEach {
            println("${it[Users.name]} lives in ${it[Cities.name]}")
        }

        println("Join with foreign key:")


        (Users innerJoin Cities).slice(Users.name, Users.cityId, Cities.name).
                select {Cities.name.eq("St. Petersburg") or Users.cityId.isNull()}.forEach {
            if (it[Users.cityId] != null) {
                println("${it[Users.name]} lives in ${it[Cities.name]}")
            }
            else {
                println("${it[Users.name]} lives nowhere")
            }
        }

        println("Functions and group by:")

        ((Cities innerJoin Users).slice(Cities.name, Users.id.count()).selectAll().groupBy(Cities.name)).forEach {
            val cityName = it[Cities.name]
            val userCount = it[Users.id.count()]

            if (userCount > 0) {
                println("$userCount user(s) live(s) in $cityName")
            } else {
                println("Nobody lives in $cityName")
            }
        }

        drop (Users, Cities)

    }
}

CRUD和各類查詢都很容易表達,也能自動建表,確實方便得很。

可是文檔沒提到schema migration,想必是沒這個功能。若是你想修改表結構,還得手動用SQL去改?這方面須要提升。

Requery

https://github.com/requery/re...

這是一個主要面向Android的Java ORM框架,爲Kotlin提供了一些額外特性。

你須要把實體聲明爲abstract class或interface,而後標上相似JPA的註解:

@Entity
abstract class AbstractPerson {

    @Key @Generated
    int id;

    @Index("name_index")                     // table specification
    String name;

    @OneToMany                               // relationships 1:1, 1:many, many to many
    Set<Phone> phoneNumbers;

    @Converter(EmailToStringConverter.class) // custom type conversion
    Email email;

    @PostLoad                                // lifecycle callbacks
    void afterLoad() {
        updatePeopleList();
    }
    // getter, setters, equals & hashCode automatically generated into Person.java
}
@Entity
public interface Person {

    @Key @Generated
    int getId();

    String getName();

    @OneToMany
    Set<Phone> getPhoneNumbers();

    String getEmail();
}

它提供了SQL DSL,看起來彷佛依賴代碼生成:

Result<Person> query = data
    .select(Person.class)
    .where(Person.NAME.lower().like("b%")).and(Person.AGE.gt(20))
    .orderBy(Person.AGE.desc())
    .limit(5)
    .get();

用Kotlin能夠寫得更簡潔:

data {
    val result = select(Person::class) where (Person::age gt 21) and (Person::name eq "Bob") limit 10
}

Kwery, Kuery, Kotliquery

https://github.com/andrewoma/...

https://github.com/x2bool/kuery

https://github.com/seratch/ko...

這三個其實是SQL庫,對JDBC作了一些封裝,提供了簡易的SQL DSL。我不想用篇幅來介紹,有興趣的朋友能夠去項目主頁看一看。

還要特別推薦Ebean ORM框架 https://ebean-orm.github.io/ 融合了JPA和Active Record的風格,成熟度相對高一些,已有必定規模的用戶羣,雖然不是專爲Kotlin設計,但做者也在使用Kotlin。

依賴注入框架

Kodein

https://github.com/SalomonBry...

用法簡單,支持scopes, modules, lazy等特性。

val kodein = Kodein {
    bind<Dice>() with provider { RandomDice(0, 5) }
    bind<DataSource>() with singleton { SqliteDS.open("path/to/file") }
}

class Controller(private val kodein: Kodein) {
    private val ds: DataSource = kodein.instance()
}

我的認爲Kodein沒有什麼亮點。

由於傳統的Spring和Guice都是能夠用的,功能和穩定性更有保證,因此建議繼續用傳統的吧。

測試框架

Spek

https://github.com/JetBrains/...

JetBrains官方支持的規格測試框架,效仿了Ruby的RSpec,代碼風格很類似,可讀性很好:

class SimpleTest : Spek({
    describe("a calculator") {
        val calculator = SampleCalculator()
    
        it("should return the result of adding the first number to the second number") {
            val sum = calculator.sum(2, 4)
            assertEquals(6, sum)
        }
    
        it("should return the result of subtracting the second number from the first number") {
            val subtract = calculator.subtract(4, 2)
            assertEquals(2, subtract)
        }
    }
})

除此以外,Java的JUnit, TestNG, Mockito等框架在Kotlin中都是可使用的。

結語

相比於Scala,Kotlin在實用性方面下了大功夫,無縫兼容Java,融入Java生態,自身也有簡潔的語法和強大的DSL能力。(想想Scala 2.10 2.11 2.12的互不兼容,以及build一個項目會下載標準庫的n個版本,例如2.11.0、2.11.一、2.11.2,也不知道實際運行的是哪一個。)

這些新興的Kotlin框架延續了Kotlin的簡潔和強大,相信它們很快就會展示出光明的前途!

相關文章
相關標籤/搜索