Kotlin DSL风格的API允许我们以半声明的方式来构造应用,例如:[code]private val log = Log.getLogger { }
fun main(args: Array
val server = HttpServer(requestLocal) {
router {
httpMethod = HttpMethod.GET
path = "/"
asyncHandler {
end("hello world!")
}
}
router {
httpMethods = listOf(GET, POST)
path = "/product/:type/:id"
asyncHandler {
statusLine {
status = OK.code
reason = OK.message
}
header {
"My-Header" to "Ohh nice"
SERVER to "Firefly kotlin DSL server"
+HttpField("Add-My-Header", "test add")
}
trailer {
"You-are-trailer" to "Crane ....."
}
val type = getRouterParameter("type")
val id = getRouterParameter("id")
log.info { "req type: $type, id: $id" }
writeJson(Response("ok", 200, Product(id, type))).end()
}
}
}
server.listen("localhost", 8080)
}[/code]在这个例子中,我们使用Kotlin DSL风格的API来设置HTTP method, path, header等,它能更清晰的表达HTTP协议的结构。
Firefly HTTP Server/Client (Kotlin版本)在协程(Coroutine)中执行业务逻辑,这意味着我们可以以同步风格的代码编写异步应用程序。编写协程同步风格的代码相比异步回调更简单,更易于阅读,并且不会影响程序的性能和伸缩性。
由于Java语言并没有原生协程(Coroutine),在未来的版本中我们考虑增加Quasar(一个JVM第三方协程库)适配器来使得Java版本的HTTP Server/Client运行在协程中。
为了让Java版本的框架更容易编写异步应用程序,增加了Spring Reactor适配器来帮助我们更流畅的构建异步应用。例如:[code]@Override
public Mono
if (request == null) {
return Mono.error(new IllegalArgumentException("The product request is required"));
}
if (request.getUserId() == null || request.getUserId().equals(0L)) {
return Mono.error(new IllegalArgumentException("The user id is required"));
}
if (CollectionUtils.isEmpty(request.getProducts())) {
return Mono.error(new IllegalArgumentException("The products must bu not empty"));
}
return db.newTransaction(c -> buy(request, c));
}
private Mono
return inventoryDAO.updateBatch(request.getProducts(), InventoryOperator.SUB, c)
.doOnSuccess(this::verifyInventory)
.flatMap(arr -> productDAO.list(toProductIdList(request), c))
.map(products -> toOrders(request, products))
.flatMap(orders -> orderDAO.insertBatch(orders, c))
.map(orderIdList -> true);
}[/code]更新日志:
增加Kotlin DSL风格的API
增加异步SQL客户端
增加Reactive stream适配器
增加Coroutine dispatcher
HTTP客户端增自动识别gzip编码
增加slf4j MDC实现
增加日志formatter
增加AffinityThreadPool
软件详情:http://gitee.com/mirrors/Firefly-Framework
来自:开源中国社区

