彩票3d字谜应用程序与Kotlin Ktor

介绍

免责声明:这个Ktor文章最初发表在Dzone 彩票3d字谜开发指南中,可以下载 这里.

谷歌制作时 kotlin. 一个 官方语言 几个月前为Android 谷歌I / O.,这种语言在Android世界迅速获得了很多人气。在服务器端,Kotlin尚未广泛采用,当涉及后端服务时,有些人似乎似乎持谨慎态度。其他开发人员说Kotlin足够成熟,我们可以安全地将其用于任何服务器应用程序,其中Java可以播放角色。
如果要使用Kotlin开发彩票3d字谜应用程序,可以从Spring MVC / 彩票3d字谜Flux,Vert.x,Vaadin等各种彩票3d字谜框架中选择,基本上可用于JVM。除了提到的框架还有 一个特定的kotlin 用于创建彩票3d字谜应用程序的库,称为Kotlin ktor.。阅读本文后,您会知道Ktor及其优势是什么以及如何在Kotlin中快速开发彩票3d字谜应用程序。

kotlin. Ktor.

彩票3d字谜应用程序框架 ktor.,本身在Kotlin中写道,意味着提供一种使用Kotlin快速创建彩票3d字谜应用程序的工具。生成的软件可以在标准的servlet容器中托管,如tomcat或独立的 纳塔蒂 例如。无论您选择的托管如何,Ktor都在大量使用Kotlin Coroutines,因此它是异步实现100%,主要是不阻止的。 KTOR不决定要使用的框架或工具,以便您可以选择您喜欢的任何日志记录,DI或模板引擎。图书馆通常是较轻的重量,仍然通过插件机制非常伸展。
归因于KOTLIN的最具相当大的优势,是其提供类型安全的建筑商的能力,也称为特定域语言(DSL.)。许多图书馆已经为DSL提供了标准API的替代品,例如Android Lib 安克,kotlin. HTML. 建造者或新发布 春天5. 框架。正如我们在即将到来的例子中所看到的,Ktor也使用此类DSL,这使得用户能够以非常声明的方式定义彩票3d字谜应用程序的端点。

示例应用程序

在下文中,我们开发了一个小的宁静(不确定,如果每个人都同意)彩票3d字谜服务 ktor.. The service uses an in-memory repository with simple Person resources, which it exposes through a JSON API. Let's look at the components.

Person 资源和存储库

According to the app's requirements, a resource "Person" is defined as a data class and the corresponding repository as an object, Kotlin's way of applying the Singleton pattern to a class.


data class Person(val name: String, val age: Int){
    var id: Int? = null
}

这 resource has two simple properties, which need to be defined when a user creates a new object, whereas the id property is set later when stored in the repository.
Person 存储库 是不值得不安的,不值得观察。它使用内部数据存储并提供常见的CRUD操作。

终点

彩票3d字谜应用程序中最重要的部分是其端点的配置,如REST API暴露。提供以下端点:

终点http方法描述
/persons得到Requests all Person resources
/persons/{id}得到Requests a specific Person resource by its ID
/persons删除Requests all Person resources to be removed
/persons/{id}删除Requests a specific Person resource to be removed by its ID
/persons邮政Requests to store a new Person resource
/得到提供一个简单的HTML页面欢迎客户

这 application won't support an update operator via PUT.

用ktor路由

现在KTOR与其结构化DSL一起发挥作用,该结构化DSL将用于定义先前所示的端点,该过程通常称为“路由”。让我们看看它是如何工作的:


fun Application.main() {
    install(DefaultHeaders)
    install(CORS) {
        maxAge = Duration.ofDays(1)
    }
    install(ContentNegotiation){
        register(ContentType.Application.Json, GsonConverter())
    }

    routing {
        get("/persons") {
            LOG.debug("Get all Person entities")
            call.respond(PersonRepo.getAll())
        }
    }
    // more routings
}

这 fundamental class in the ktor library is Application, which represents a configured and eventually running web service instance. In the snippet, an extension function main() is defined on Application, in which we can call functions defined in Application directly, without additional qualifiers. We do exactly that by invoking install() multiple times, a function for adding certain ApplicationFeatures into the request processing pipeline of the application. These features are optional, and the user can choose from various types. The only interesting feature in the shown example is ContentNegotiation, which is used for the (de-)serialization of Kotlin objects to and from JSON, respectively. We use Gson as a backing technology.
这 routing itself is shown with the 得到 endpoint for retrieving all Person resources here. It's fairly straight-forward since the result of the repository call getAll() is just delegated back to the client. The call.respond() invocation eventually reaches the GsonSupport feature taking care of transforming the Person into its JSON representation. The same happens for the remaining four REST endpoints, which are not shown explicitly here.

HTML Builder.

Ktor的另一个很酷的功能是与其他Kotlin DSL相同,如HTML Builder,您可以找到 GitHub.. By adding a single additional dependency to a ktor app, this builder is useable with the extension function call.respondHtml(), which expects type-safe HTML as input. In the following example, we include a simple greeting to the readers, which the web service exposes as its index page.


get("/") {
    call.respondHtml {
        head {
            title("ktor. Example Application")
        }
        body {
            h1 { +"Hello DZone Readers" }
            p {
                +"How are you doing?"
            }
        }
    }
}

启动应用程序

After having done the configuration of a ktor application, there's still a need to start it through a regular main method. In the demo, a 纳塔蒂 通过执行以下操作,服务器启动独立:


fun main(args: Array) {
    embeddedServer(Netty, 8080, module = Application::main).start(wait = true)
}

这 starting is made pretty simple by just calling the embeddedServer() method with a Netty environment, a port and the module to be started, which happens to be the thingy defined in the Application.main() extension function from the previously shown example.

测试

A web framework or library is only applicable if it comes with integrated testing means, which ktor actually does. Since the 得到 routing for retrieving all Person resources was already shown, let's have a look at how the endpoint can be tested.


@Test
fun getAllPersonsTest() = withTestApplication(Application::main) {
    val person = savePerson(gson.toJson(Person("Bert", 40)))
    val person2 = savePerson(gson.toJson(Person("Alice", 25)))
    handleRequest(HttpMethod.Get, "/persons") {
        addHeader("接受", json)
    }.response.let {
        assertEquals(HttpStatusCode.OK, it.status())
        val response = gson.fromJson(it.content, Array::class.java)
        response.forEach { println(it) }
        response.find { it.name == person.name } ?: fail()
        response.find { it.name == person2.name } ?: fail()
    }
    assertEquals(2, PersonRepo.getAll().size)
}

This one is quite simple: Two resource objects are added to the repository, then the 得到 request is executed and some assertions are done against the web service response. The important part is withTestApplication(), which ktor offers through its testing module and makes it possible to directly test the Application.
本文基本上呈现,值得了解ktor 彩票3d字谜应用程序的一切值得了解。有关更多详细信息,我推荐 ktor. 主页或者 样本 包含在ktor存储库中。

外带

在本文中,我们看看Kotlin 彩票3d字谜服务库 ktor. 这提供了简单的手段,用于非常快速地在Kotlin中写入轻质彩票3d字谜应用程序。 Ktor大量使用Kotlin的美丽功能。它尤其是利用DSL,金冠和扩展功能,所有这些都使语言和Ktor本身如此优雅。如果您想在Kotlin中的彩票3d字谜应用程序开始,Ktor是一个很棒的工具,因为它在“简单简单,可用的复杂”之后它的简单且非常可扩展。
您可以找到开发的彩票3d字谜应用程序的完整源代码 GitHub..

2 thoughts on “彩票3d字谜应用程序与Kotlin Ktor

发表评论

您的电子邮件地址不会被公开。 必需的地方已做标记 *