资讯专栏INFORMATION COLUMN

Kotlin框架巡礼

_Suqin / 963人阅读

摘要:框架官方支持的框架,风格颇为类似,并且充分发挥了的强类型优势。这是一个主要面向的框架,为提供了一些额外特性。依赖注入框架用法简单,支持等特性。

首先要说明,Kotlin支持你所知道的所有Java框架和库,包括但不限于Spring全家桶、Guice、Hibernate、MyBatis、Jackson等,甚至有人在用Kotlin写Spark大数据程序,因此Kotlin不需要专门的框架。因此,为Kotlin开发框架的人,都是怀着满满的爱!

Kotlin现在主要流行于Android开发,我是搞后端开发的,不熟悉Android,就不妄言了。这篇文章主要介绍后端框架,包括Web、SQL、依赖注入、测试这些方面。

Web框架 Wasabi

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

极简的Web框架,基于Netty构建,编程风格效仿了Ruby的Sinatra和Node.js的Express。

Java也有个效仿Sinatra风格的Web框架,叫Spark(是的,与某大数据框架重名了)。

使用很简单:

</>复制代码

  1. var server = AppServer()
  2. server.get("/", { response.send("Hello World!") })
  3. server.start()

也可以这么写:

</>复制代码

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

加一个前置拦截器(next()表示进入下一步处理):

</>复制代码

  1. server.get("/",
  2. {
  3. val log = Log()
  4. log.info("URI requested is ${request.uri}")
  5. next()
  6. },
  7. {
  8. response.send("Hello World!", "application/json")
  9. }
  10. )

获取参数:

</>复制代码

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

</>复制代码

  1. server.get("/customer", { val customerName = request.queryParams["name"] } )

为了提供可维护性,可以在别处定义一个方法,在程序入口引用它:

</>复制代码

  1. 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:

</>复制代码

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

HTML Layout:

</>复制代码

  1. class DefaultLayout() : HtmlLayout() {
  2. override fun render(context: ActionContext, mainView: HtmlView) {
  3. head {
  4. title("Kara Demo Title")
  5. stylesheet(DefaultStyles())
  6. }
  7. body {
  8. h1("Kara Demo Site")
  9. div(id="main") {
  10. renderView(context, mainView)
  11. }
  12. a(text="Kara is developed by Tiny Mission", href="http://tinymission.com")
  13. }
  14. }
  15. }

Forms:

</>复制代码

  1. class BookForm(val book : Book) : HtmlView() {
  2. override fun render(context: ActionContext) {
  3. h2("Book Form")
  4. formFor(book, "/updatebook", FormMethod.Post) {
  5. p {
  6. labelFor("title")
  7. textFieldFor("title")
  8. }
  9. p {
  10. labelFor("isPublished", "Is Published?")
  11. checkBoxFor("isPublished")
  12. }
  13. }
  14. }
  15. }

CSS:

</>复制代码

  1. class DefaultStyles() : Stylesheet() {
  2. override fun render() {
  3. s("body") {
  4. backgroundColor = c("#f0f0f0")
  5. }
  6. s("#main") {
  7. width = 85.percent
  8. backgroundColor = c("#fff")
  9. margin = box(0.px, auto)
  10. padding = box(1.em)
  11. border = "1px solid #ccc"
  12. borderRadius = 5.px
  13. }
  14. s("input[type=text], textarea") {
  15. padding = box(4.px)
  16. width = 300.px
  17. }
  18. s("textarea") {
  19. height = 80.px
  20. }
  21. s("table.fields") {
  22. s("td") {
  23. padding = box(6.px, 3.px)
  24. }
  25. s("td.label") {
  26. textAlign = TextAlign.right
  27. }
  28. s("td.label.top") {
  29. verticalAlign = VerticalAlign.top
  30. }
  31. }
  32. }
  33. }

其实就是在写Kotlin代码,显然你可以自行扩展出更多的DSL,还可以用面向对象或函数式的方式来复用。

Controllers 像Spring MVC和Django的风格

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

</>复制代码

  1. object Home {
  2. val layout = DefaultLayout()
  3. Get("/")
  4. class Index() : Request({
  5. karademo.views.home.Index()
  6. })
  7. Get("/test")
  8. class Test() : Request({
  9. TextResult("This is a test action, yo")
  10. })
  11. Post("/updatebook")
  12. class Update() : Request({
  13. redirect("/forms")
  14. })
  15. Get("/complex/*/list/:id")
  16. Complex(id : Int) : Request({
  17. TextResult("complex: ${params[0]} id = ${params["id"]}")
  18. })
  19. }
当然也有拦截器,在这里叫Middleware

实现这个接口并绑定到路由路径就可以了:

</>复制代码

  1. /**
  2. * Base class for Kara middleware.
  3. * Middleware is code that is injected inside the request pipeline,
  4. * either before or after a request is handled by the application.
  5. */
  6. abstract class Middleware() {
  7. /**
  8. * Gets called before the application is allowed to handle the request.
  9. * Return false to stop the request pipeline from executing anything else.
  10. */
  11. abstract fun beforeRequest(context : ActionContext) : Boolean
  12. /**
  13. * Gets called after the application is allowed to handle the request.
  14. * Return false to stop the request pipeline from executing anything else.
  15. */
  16. abstract fun afterRequest(context : ActionContext) : Boolean
  17. }

</>复制代码

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

综合来说,Kara确实是比较优秀的web框架。

但有一点不好,默认使用3000端口,与Rails重复了。

SQL框架 Exposed

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

JetBrains官方支持的SQL/ORM框架,风格颇为类似Django ORM,并且充分发挥了Kotlin的强类型优势。

项目主页有很长一段示例代码,全程都是强类型,非常流畅,令人赏心悦目:

</>复制代码

  1. import org.jetbrains.exposed.sql.*
  2. import org.jetbrains.exposed.sql.transactions.transaction
  3. import org.jetbrains.exposed.sql.SchemaUtils.create
  4. import org.jetbrains.exposed.sql.SchemaUtils.drop
  5. object Users : Table() {
  6. val id = varchar("id", 10).primaryKey() // Column
  7. val name = varchar("name", length = 50) // Column
  8. val cityId = (integer("city_id") references Cities.id).nullable() // Column
  9. }
  10. object Cities : Table() {
  11. val id = integer("id").autoIncrement().primaryKey() // Column
  12. val name = varchar("name", 50) // Column
  13. }
  14. fun main(args: Array) {
  15. Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
  16. transaction {
  17. create (Cities, Users)
  18. val saintPetersburgId = Cities.insert {
  19. it[name] = "St. Petersburg"
  20. } get Cities.id
  21. val munichId = Cities.insert {
  22. it[name] = "Munich"
  23. } get Cities.id
  24. Cities.insert {
  25. it[name] = "Prague"
  26. }
  27. Users.insert {
  28. it[id] = "andrey"
  29. it[name] = "Andrey"
  30. it[cityId] = saintPetersburgId
  31. }
  32. Users.insert {
  33. it[id] = "sergey"
  34. it[name] = "Sergey"
  35. it[cityId] = munichId
  36. }
  37. Users.insert {
  38. it[id] = "eugene"
  39. it[name] = "Eugene"
  40. it[cityId] = munichId
  41. }
  42. Users.insert {
  43. it[id] = "alex"
  44. it[name] = "Alex"
  45. it[cityId] = null
  46. }
  47. Users.insert {
  48. it[id] = "smth"
  49. it[name] = "Something"
  50. it[cityId] = null
  51. }
  52. Users.update({Users.id eq "alex"}) {
  53. it[name] = "Alexey"
  54. }
  55. Users.deleteWhere{Users.name like "%thing"}
  56. println("All cities:")
  57. for (city in Cities.selectAll()) {
  58. println("${city[Cities.id]}: ${city[Cities.name]}")
  59. }
  60. println("Manual join:")
  61. (Users innerJoin Cities).slice(Users.name, Cities.name).
  62. select {(Users.id.eq("andrey") or Users.name.eq("Sergey")) and
  63. Users.id.eq("sergey") and Users.cityId.eq(Cities.id)}.forEach {
  64. println("${it[Users.name]} lives in ${it[Cities.name]}")
  65. }
  66. println("Join with foreign key:")
  67. (Users innerJoin Cities).slice(Users.name, Users.cityId, Cities.name).
  68. select {Cities.name.eq("St. Petersburg") or Users.cityId.isNull()}.forEach {
  69. if (it[Users.cityId] != null) {
  70. println("${it[Users.name]} lives in ${it[Cities.name]}")
  71. }
  72. else {
  73. println("${it[Users.name]} lives nowhere")
  74. }
  75. }
  76. println("Functions and group by:")
  77. ((Cities innerJoin Users).slice(Cities.name, Users.id.count()).selectAll().groupBy(Cities.name)).forEach {
  78. val cityName = it[Cities.name]
  79. val userCount = it[Users.id.count()]
  80. if (userCount > 0) {
  81. println("$userCount user(s) live(s) in $cityName")
  82. } else {
  83. println("Nobody lives in $cityName")
  84. }
  85. }
  86. drop (Users, Cities)
  87. }
  88. }

CRUD和各种查询都很容易表达,也能自动建表,确实方便得很。

但是文档没提到schema migration,想必是没这个功能。如果你想修改表结构,还得手动用SQL去改?这方面需要提高。

Requery

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

这是一个主要面向Android的Java ORM框架,为Kotlin提供了一些额外特性。

你需要把实体声明为abstract class或interface,然后标上类似JPA的注解:

</>复制代码

  1. @Entity
  2. abstract class AbstractPerson {
  3. @Key @Generated
  4. int id;
  5. @Index("name_index") // table specification
  6. String name;
  7. @OneToMany // relationships 1:1, 1:many, many to many
  8. Set phoneNumbers;
  9. @Converter(EmailToStringConverter.class) // custom type conversion
  10. Email email;
  11. @PostLoad // lifecycle callbacks
  12. void afterLoad() {
  13. updatePeopleList();
  14. }
  15. // getter, setters, equals & hashCode automatically generated into Person.java
  16. }

</>复制代码

  1. @Entity
  2. public interface Person {
  3. @Key @Generated
  4. int getId();
  5. String getName();
  6. @OneToMany
  7. Set getPhoneNumbers();
  8. String getEmail();
  9. }

它提供了SQL DSL,看起来似乎依赖代码生成:

</>复制代码

  1. Result query = data
  2. .select(Person.class)
  3. .where(Person.NAME.lower().like("b%")).and(Person.AGE.gt(20))
  4. .orderBy(Person.AGE.desc())
  5. .limit(5)
  6. .get();

用Kotlin可以写得更简洁:

</>复制代码

  1. data {
  2. val result = select(Person::class) where (Person::age gt 21) and (Person::name eq "Bob") limit 10
  3. }
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等特性。

</>复制代码

  1. val kodein = Kodein {
  2. bind() with provider { RandomDice(0, 5) }
  3. bind() with singleton { SqliteDS.open("path/to/file") }
  4. }
  5. class Controller(private val kodein: Kodein) {
  6. private val ds: DataSource = kodein.instance()
  7. }

个人认为Kodein没有什么亮点。

因为传统的Spring和Guice都是可以用的,功能和稳定性更有保证,所以建议继续用传统的吧。

测试框架 Spek

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

JetBrains官方支持的规格测试框架,效仿了Ruby的RSpec,代码风格很相似,可读性很好:

</>复制代码

  1. class SimpleTest : Spek({
  2. describe("a calculator") {
  3. val calculator = SampleCalculator()
  4. it("should return the result of adding the first number to the second number") {
  5. val sum = calculator.sum(2, 4)
  6. assertEquals(6, sum)
  7. }
  8. it("should return the result of subtracting the second number from the first number") {
  9. val subtract = calculator.subtract(4, 2)
  10. assertEquals(2, subtract)
  11. }
  12. }
  13. })

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

结语

相比于Scala,Kotlin在实用性方面下了大功夫,无缝兼容Java,融入Java生态,自身也有简洁的语法和强大的DSL能力。(想一想Scala 2.10 2.11 2.12的互不兼容,以及build一个项目会下载标准库的n个版本,例如2.11.0、2.11.1、2.11.2,也不知道实际运行的是哪个。)

这些新兴的Kotlin框架延续了Kotlin的简洁和强大,相信它们很快就会展现出光明的前途!

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66645.html

相关文章

  • 毫无色彩的二哲和他的巡礼之年

    摘要:前戏今年,对于我个人而言遭遇了三个重大的转折点。尽可能的把沟通成本用约定和文档降低。学习的这一年可以说年的学习,在上半年的精力,放在了技术上。而下半年则相反。 前戏 今年,对于我个人而言遭遇了三个重大的转折点。 15年9月大三休学创业,16年9月重新复学大三 在2016年4月顺利引进天使轮,公司从厦门集美区搬到了深圳南山区 16年底,我们正在准备接入A轮 16年与15年相比,总体来...

    Alex 评论0 收藏0
  • 初探Kotlin+SpringBoot联合编程

    摘要:是一门最近比较流行的静态类型编程语言,而且和一样同属系。这个生成的构造函数是合成的,因此不能从或中直接调用,但可以使用反射调用。 showImg(https://segmentfault.com/img/remote/1460000012958496); Kotlin是一门最近比较流行的静态类型编程语言,而且和Groovy、Scala一样同属Java系。Kotlin具有的很多静态语言...

    xiaokai 评论0 收藏0
  • 2016年前端盘点合集

    摘要:年已经过去,这一年前端领域发生了什么有哪些技术和项目引人注目工程师们观点和看法又有怎样的变化在此,整理了一些对过去的年盘点的资料,一是希望能借此提高自己的姿势水平,二是希望能为年的学习有所指导。 2016年已经过去,这一年前端领域发生了什么?有哪些技术和项目引人注目?工程师们观点和看法又有怎样的变化?在此,整理了一些对过去的2016年盘点的资料,一是希望能借此提高自己的姿势水平,二是希...

    aisuhua 评论0 收藏0
  • Kotlin + Spring Boot服务端开发

    摘要:是什么著名厂商开发的基于的静态类型编程语言,声称。语法近似和,且已活跃在开发领域,被誉为平台的。各有千秋,我更认同改写字节码。的作用是防止敏感字段被泄露到中,的作用是软删除数据不可见,但没有真的删除。 Kotlin是什么? 著名IDE厂商JetBrains开发的基于JVM的静态类型编程语言,声称100% interoperable with Java。Kotlin是由工程师设计的,各种...

    e10101 评论0 收藏0

发表评论

0条评论

_Suqin

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<