javascript
kotlin dsl_Spring Webflux – Kotlin DSL –实现的演练
kotlin dsl
在以前的博客文章中,我描述了Spring Web Framework中的響應式編程支持Spring Webflux如何使用基于Kotlin的DSL使用戶能夠以非常直觀的方式描述路由。 在這里,我想探索一些底層實現。
描述一組端點的樣本DSL看起來像這樣:
package sample.routesimport org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.MediaType.APPLICATION_JSON import org.springframework.web.reactive.function.server.router import sample.handler.MessageHandler@Configuration class AppRoutes(private val messageHandler: MessageHandler) {@Beanfun apis() = router {(accept(APPLICATION_JSON) and "/messages").nest {GET("/", messageHandler::getMessages)POST("/", messageHandler::addMessage)GET("/{id}", messageHandler::getMessage)PUT("/{id}", messageHandler::updateMessage)DELETE("/{id}", messageHandler::deleteMessage)}}}為了分析樣本,讓我從一個較小的工作示例開始:
import org.junit.Test import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.web.reactive.function.server.ServerResponse.ok import org.springframework.web.reactive.function.server.routerclass AppRoutesTest {@Testfun testSimpleGet() {val routerFunction = router {GET("/isokay", { _ -> ok().build() })}val client = WebTestClient.bindToRouterFunction(routerFunction).build()client.get().uri("/isokay").exchange().expectStatus().isOk} }路由定義的核心是“路由器”功能:
import org.springframework.web.reactive.function.server.router ... val routerFunction = router {GET("/isokay", { _ -> ok().build() }) }通過以下方式定義:
fun router(routes: RouterFunctionDsl.() -> Unit) = RouterFunctionDsl().apply(routes).router()參數“ routes”是lambda表達式的一種特殊類型, 稱為帶接收器的Lambda表達式 。 這意味著在路由器功能的上下文中,此lambda表達式只能由“ RouterFunctionDsl”實例調用,這是在函數主體中使用apply方法完成的操作,這也意味著在lambda表達式主體中“此”是“ RouterFunctionDsl”的實例。 知道了這一點,便可以訪問“ RouterFunctionDsl”的方法,該方法之一就是示例中使用的GET,GET的定義如下:
fun GET(pattern: String, f: (ServerRequest) -> Mono<ServerResponse>) {... }還有其他方式表示相同的端點:
GET("/isokay2")({ _ -> ok().build() })在Kotlin中非常巧妙地實現為:
fun GET(pattern: String): RequestPredicate = RequestPredicates.GET(pattern)operator fun RequestPredicate.invoke(f: (ServerRequest) -> Mono<ServerResponse>) {... }此處,使用模式的GET返回一個“ RequestPredicate”,已為其定義了一個擴展函數 (在DSL的上下文中),稱為invoke,而后者又是一個特別命名的運算符 。
或第三種方式:
"/isokay" { _ -> ok().build() }這是通過在String類型上添加擴展函數來實現的,并通過以下方式定義:
operator fun String.invoke(f: (ServerRequest) -> Mono<ServerResponse>) {... }我覺得Spring Webflux很好地利用了Kotlin DSL,使其中一些路由定義易于閱讀,同時保持簡潔。
這應該提供足夠的入門知識,以探索Spring Webflux中Routing DSL的源代碼。
我的示例可在此處的github存儲庫中找到 – https://github.com/bijukunjummen/webflux-route-with-kotlin
翻譯自: https://www.javacodegeeks.com/2017/09/spring-webflux-kotlin-dsl-walkthrough-implementation.html
kotlin dsl
總結
以上是生活随笔為你收集整理的kotlin dsl_Spring Webflux – Kotlin DSL –实现的演练的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魅蓝3s刷机(魅蓝3s刷机包纯净版)
- 下一篇: WeGame下载速度慢怎么解决?