软件简介
什么是Firefly?
Firefly是一个Java异步Web框架,它能帮助您方便和快速的创建web应用。其主要功能包括:异步HTTP服务器/客户端,异步TCP服务器/客户端,数据库访问,IOC框架等。部署Firefly不需要任何额外的web容器。Firefly使用高度可伸缩的SEDA架构能充分发挥硬件的性能。
事件驱动
传统的阻塞模型会消耗大量的线程,从而导致占用的大量内存和上下文切换开销。Firefly的API使用事件驱动模型,用很少的线程去处理很高的并发请求。
函数编程
Firefly提供了函数风格和链式调用API来编写网络应用程序,它可以让您使用极简主义的代码,流畅的开发网络应用程序。例如:
public class HelloHTTPServerAndClient {
public static void main(String[] args) {
Phaser phaser = new Phaser(2);
HTTP2ServerBuilder httpServer = $.httpServer();
httpServer.router().get("/").handler(ctx -> ctx.write("hello world! ").next())
.router().get("/").handler(ctx -> ctx.end("end message"))
.listen("localhost", 8080);
$.httpClient().get("http://localhost:8080/").submit()
.thenAccept(res -> System.out.println(res.getStringBody()))
.thenAccept(res -> phaser.arrive());
phaser.arriveAndAwaitAdvance();
httpServer.stop();
$.httpClient().stop();
}
}
Kotlin支持
Firefly同样提供了Kotlin DSL风格的API,Kotlin DSL以半声明的方式构造程序,能清晰的表达程序的结构和意图。例如:
fun main(args: Array) {
HttpServer {
router {
httpMethod = HttpMethod.GET
path = "/"
asyncHandler {
end("hello world!")
}
}
}.listen("localhost", 8080)
}
fun main(args: Array): Unit = runBlocking {
val msg = firefly.httpClient().get("http://localhost:8080").asyncSubmit().stringBody
println(msg)
}
Firefly Kotlin HTTP
服务器和客户端使用协程(coroutine)消除回调风格的代码,能让程序变得更简单清晰,并保留了异步IO的性能与伸缩性。
更多详细的用例可以在Firefly的文档中找到。