javascript
kotlin dsl_Spring Webflux – Kotlin DSL –实现的演练
kotlin dsl
在以前的博客文章中,我描述了Spring Web Framework中的響應(yīng)式編程支持Spring Webflux如何使用基于Kotlin的DSL使用戶能夠以非常直觀的方式描述路由。 在這里,我想探索一些底層實(shí)現(xiàn)。
描述一組端點(diǎn)的樣本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)}}}為了分析樣本,讓我從一個(gè)較小的工作示例開始:
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()參數(shù)“ routes”是lambda表達(dá)式的一種特殊類型, 稱為帶接收器的Lambda表達(dá)式 。 這意味著在路由器功能的上下文中,此lambda表達(dá)式只能由“ RouterFunctionDsl”實(shí)例調(diào)用,這是在函數(shù)主體中使用apply方法完成的操作,這也意味著在lambda表達(dá)式主體中“此”是“ RouterFunctionDsl”的實(shí)例。 知道了這一點(diǎn),便可以訪問“ RouterFunctionDsl”的方法,該方法之一就是示例中使用的GET,GET的定義如下:
fun GET(pattern: String, f: (ServerRequest) -> Mono<ServerResponse>) {... }還有其他方式表示相同的端點(diǎn):
GET("/isokay2")({ _ -> ok().build() })在Kotlin中非常巧妙地實(shí)現(xiàn)為:
fun GET(pattern: String): RequestPredicate = RequestPredicates.GET(pattern)operator fun RequestPredicate.invoke(f: (ServerRequest) -> Mono<ServerResponse>) {... }此處,使用模式的GET返回一個(gè)“ RequestPredicate”,已為其定義了一個(gè)擴(kuò)展函數(shù) (在DSL的上下文中),稱為invoke,而后者又是一個(gè)特別命名的運(yùn)算符 。
或第三種方式:
"/isokay" { _ -> ok().build() }這是通過在String類型上添加擴(kuò)展函數(shù)來實(shí)現(xiàn)的,并通過以下方式定義:
operator fun String.invoke(f: (ServerRequest) -> Mono<ServerResponse>) {... }我覺得Spring Webflux很好地利用了Kotlin DSL,使其中一些路由定義易于閱讀,同時(shí)保持簡潔。
這應(yīng)該提供足夠的入門知識(shí),以探索Spring Webflux中Routing DSL的源代碼。
我的示例可在此處的github存儲(chǔ)庫中找到 – https://github.com/bijukunjummen/webflux-route-with-kotlin
翻譯自: https://www.javacodegeeks.com/2017/09/spring-webflux-kotlin-dsl-walkthrough-implementation.html
kotlin dsl
總結(jié)
以上是生活随笔為你收集整理的kotlin dsl_Spring Webflux – Kotlin DSL –实现的演练的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魅蓝3s刷机(魅蓝3s刷机包纯净版)
- 下一篇: gradle idea java ssm