Kotlin & Vertx

Kotlin 是一门好语言,值得大家了解一下。

Vertx 是一个好框架,也值得大家了解一下。

Kotlin

写过js,也写过一点点go,主力一直是java。用了kotlin,貌似找到了常用语言的平衡点了。

Kotlin 拥有一些偏函数式的语法(java8 也引入了一些),提供了相当多便捷的api与一些高阶函数。从两天的试用,以及今天搞得这个 Vertx web 项目,从中体会到最爽的有两点:

  • 支持“带接收者得函数字面值”(允许你直接指定函数的receiver的类型)这一特性。这个特性,在go里面经常看到。然而,java没有,java8也没有...
  • 支持扩展函数(或许是我见识短,这功能爆炸了)

一直很期待可以指定receiver这个功能。有了这个特性,那么写的函数,可以直接被调用者使用。

Vertx

vertx 风格和node的express框架思想一致的,换了一种java的实现。不得不说,node的express 启发了很多其他语言的web框架设计。java的vertx,以及go里面的很多web框架(martin...),很多都有express的影子(难道是我先入为主?)

相比传统的基于Servlet的java web框架,vertx这种基于封装底层通信的框架,在速度上和内存占用上比较有优势。曾经为了在768M内存的docker容器上跑web应用,先是用相对较轻量级的spring-boot,勉强可以跑。然后又用了Node 的 express,这个毫无压力。

终于有一个java版本的这种web框架,整个项目打完包,包括依赖的 lib,整个才4-5M的大小(主要是lib大小),太轻量了。

下面就看看 Kotlin + Vertx 写的web项目,展示下kotlin的魅力。你要是比较懒的话,想直接check out代码,github库在这里

Kotlin & Vertx

1.maven 配置

按照kotlin和vertx官方的配置。
```xml

4.0.0

<groupId>vertx</groupId>
<artifactId>com.vertx</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>com.tt.vertx.HelloWorlds</Main-Class>
<Main-Verticle>com.tt.vertx.HelloWorlds</Main-Verticle>
</manifestEntries>
</transformer>
</transformers>
<artifactSet/>
<outputFile>${project.build.directory}/${project.artifactId}-${project.version}-fat.jar</outputFile>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<source>src/main/java</source>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<phase>process-test-sources</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs></sourceDirs>
</configuration>
</execution>
</executions>
</plugin> </plugins>
</build> <dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
<properties>
<kotlin.version>1.0.3</kotlin.version>
</properties>

```

2.程序入口

和spring-boot 一样,vertx 的程序入口也是一个静态的main函数。

class  HelloWorlds : AbstractVerticle() {

    companion object{
@JvmStatic fun main(args: Array<String>){
var vertx = Vertx.vertx()
vertx.deployVerticle(HelloWorlds())
}
} override fun start() {
var router = customRouter(vertx)
println("server running on 8888")
vertx.createHttpServer().requestHandler({ handler -> router.accept(handler)}).listen(8888)
}
}

如果写过nodejs应用,这段代码看起来就很简单了。继承vertx的启动类,在启动的时候,设置路由,绑定http server的端口。

注意

和普通的kotlin运行类不一样,入口主类需要打jar包的时候,主方法(main)一定是要是java的标准静态方法. 需要加 @JvmStatic 标注一下。否则运行打出来的jar包,会找不到静态主入口。

在这里,封装了一下路由,提取到了单独的文件中。

3.路由设置

fun customRouter(vertx : Vertx) : Router {
var router = Router.router(vertx)
router.route("/").handler({c -> c.response().html().end("hello world")})
router.route("/json").handler({c -> c.response().json().end(Json.encode(Entity("name","sss")))})
return router
} fun HttpServerResponse.html() : HttpServerResponse {
return this.putHeader("content-type","text/html")
} fun HttpServerResponse.json() : HttpServerResponse {
return this.putHeader("content-type","application/json; charset=utf-8")
}

让我觉得kotlin拯救了我的地方就在这一段路由代码里。

先看一下,之前用纯java写的路由版本是什么样的吧,对比一下。

java版本:

router.route("/").handler(context -> context.response().putHeader("content-type","text/html").end("hello world"));
router.route("/json").handler(context -> {
context.response().putHeader("content-type","application/json; charset=utf-8")
.end(Json.encodePrettily(new Entity("hello","world")));
});

在java版本里面,给每个请求加header的时候,是要加 .putHeader("content-type","xxxx") 的。

试想一下,如果我们有上百个路由的话,每个头里面都要指定这些header,多痛苦。根据经验,我们可能想把它提出来,当做一个方法。于是我们需要写一个工具类之类的,给context.response()的结果 HttpServerResponse 加上header,然后再返回这个 HttpServerResponse,最直观的大概写法应该是:

SomeUtil.setHeader(context.response()).end('xxx')

不管怎么说,因为java的语法限制,我们貌似只能这么写(如果有更好的方法,请大家共享一下)。

看一下kotlin版本的,把加header的操作提了出来,弄成了两个函数。这两个函数是函数接收字面量和扩展函数的结合体,使用扩展函数,这是个,也必须声明一个函数的接受者类型。
我们定义html() 和 json() 函数, 这两个方法只能用HttpServerResponse 去执行它,并且返回执行后的该 HttpServerResponse。 在扩展函数里面,this指向的是该函数的调用者。语法官方有详细文档,就少说了(好多语法我也没有看完 ORZ )。

这个特性超级好用,尤其是在这种链式的调用里面,我们不用在去另写写转换方法,不用在把要转换的对象当参数来回传递了。

4. 还有一个bean 对象

data class Entity(var name:String,var description:String){}

第一次写这个bean的时候,我写错了,无论如何,在路由里面,就是无法取到该bean构造后的值。看了官方文档才知道,这个类是需要加一个data前缀的,这样才会生成 equals ,hashCode ,Setter, Getter 等这些方法。

另外一些感想

主要代码都在这里了,完整的代码在这里

用kotlin , 感觉很幸福,相见恨晚。

代码写的少,对java 是一种强力的补充。它和java之间,完全可以相互调用,是一门很不错的语言,以后可以慢慢用起来了,还有很多东西值得去探索。

还有一点还是提一提吧,kotlin亲爹jetbrains, Idea 亲爹也是 jetbrains。Idea对自家的这门语言支持的相当的不错,大家都可以试试。另: 放弃Eclipse吧,别再折磨自己啦。

Kotlin Vertx的更多相关文章

  1. Kotlin & Vertx 构建web服务

    感想 Kotlin 是一门好语言,值得大家了解一下. Vertx 是一个好框架,也值得大家了解一下. Kotlin 写过js,也写过一点点go,主力一直是java.用了kotlin,貌似找到了常用语言 ...

  2. kotlin和vertx和mongo写的一个服务器验证登陆功能(很简陋)

    包结构长这个样子: server包:(服务器相关配置) HttpServer:用ver.x创建了一个http服务器,把接收到的req请求传入RPCRequest中: RPCRequest:解析请求bo ...

  3. Kotlin的Lambda表达式以及它们怎样简化Android开发(KAD 07)

    作者:Antonio Leiva 时间:Jan 5, 2017 原文链接:https://antonioleiva.com/lambdas-kotlin/ 由于Lambda表达式允许更简单的方式建模式 ...

  4. 用Kotlin实现Android定制视图(KAD 06)

    作者:Antonio Leiva 时间:Dec 27, 2016 原文链接:https://antonioleiva.com/custom-views-android-kotlin/ 在我们阅读有关c ...

  5. Kotlin与Android SDK 集成(KAD 05)

    作者:Antonio Leiva 时间:Dec 19, 2016 原文链接:https://antonioleiva.com/kotlin-integrations-android-sdk/ 使用Ko ...

  6. Kotlin的android扩展:对findViewById说再见(KAD 04)

    作者:Antonio Leiva 时间:Dec 12, 2016 原文链接:http://antonioleiva.com/kotlin-android-extensions/ 你也许已厌倦日复一日使 ...

  7. Kotlin类:功能更强、而更简洁(KAD 03)

    作者:Antonio Leiva 时间:Dec 7, 2016 原文链接:http://antonioleiva.com/classes-kotlin/ Kotlin类尽可能简单,这样用较少的代码完成 ...

  8. Kotlin中变量不同于Java: var 对val(KAD 02)

    原文标题:Variables in Kotlin, differences with Java. var vs val (KAD 02) 作者:Antonio Leiva 时间:Nov 28, 201 ...

  9. 用Kotlin创建第一个Android项目(KAD 01)

    原文标题:Create your first Android project using Kotlin (KAD 01) 作者:Antonio Leiva 时间:Nov 21, 2016 原文链接:h ...

随机推荐

  1. c# 另存为excel

    去网上找了一下  看了一个比较简单的新建excel然后另存为. 要引用Microsoft.Office.Interop.Excel命名空间,如果没有的话 ,百度比我懂. 直接付代码: Microsof ...

  2. java集合类遍历删除方法测试以及使用场景记录

    package test0; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java. ...

  3. 14-利用SVD简化数据

    参考:http://blog.csdn.net/geekmanong/article/details/50494936 http://www.2cto.com/kf/201503/383087.htm ...

  4. Oracle EBS-SQL (PO-10):检查过期采购未接收订单.sql

    Select pha.segment1               采购订单,            MSI.SEGMENT1             物料编码,           MSI.DESC ...

  5. [Django] Windows 下安装 配置Pinax 工程

    Pinax 是一个基于Django开发的脚手架,有一些现成的模板和功能模块可以使用,方便快速有效的开发一个Django项目.下面举个例子如何安装一个pinax项目到集成开发环境Aptana里面. 先从 ...

  6. Android第三方应用分享图文到微信朋友圈 & 微信回调通知分享状态

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWQAAAKUCAIAAAC8A9XzAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWX ...

  7. Mobile Service更新和 Notification Hub 对Android的支持

    本周,我们要推出一些更新,使移动服务成为移动应用程序更强大.更灵活的后端,同时推出一个与移动服务或网站结合使用的免费 20MB SQL 数据库,并且将支持通过Notification Hub中的 GC ...

  8. jQuery背景跟随鼠标移动的网页导航

    首页 PSD模板 CSS模板 特效插件 源码下载 酷站欣赏 建站资源 建站教程 心境之旅 在线留言 设为首页 加入收藏 我要投稿 联系站长 Search     首页 PSD模板 CSS模板 特效插件 ...

  9. iOS多线程系列(2)

    前面了iOS的NSThread方法来实现多线程,这篇就简单的讲讲NSOperation和NSOperationQueue. NSOperation是一个抽象类,定义一个要执行的任务.NSOperati ...

  10. 配置oracle账号密码永不过期

    查看用户的proifle是哪个,一般是default: sql>SELECT username,PROFILE FROM dba_users; 查看指定概要文件(如default)的密码有效期设 ...