Kotlin 支援

此框架也已改進以支援 Kotlin lambda 函數,因此現在您可以結合 Kotlin 語言和 Spring Integration 流程定義

@Bean
@Transformer(inputChannel = "functionServiceChannel")
fun kotlinFunction(): (String) -> String {
    return { it.toUpperCase() }
}

@Bean
@ServiceActivator(inputChannel = "messageConsumerServiceChannel")
fun kotlinConsumer(): (Message<Any>) -> Unit {
    return { print(it) }
}

@Bean
@InboundChannelAdapter(value = "counterChannel",
        poller = Poller(fixedRate = "10", maxMessagesPerPoll = "1"))
fun kotlinSupplier(): () -> String {
    return { "baz" }
}

Kotlin 協程

從 6.0 版本開始,Spring Integration 提供 Kotlin 協程 的支援。現在 suspend 函數和 kotlinx.coroutines.Deferred & kotlinx.coroutines.flow.Flow 回傳類型可用於服務方法

@ServiceActivator(inputChannel = "suspendServiceChannel", outputChannel = "resultChannel")
suspend fun suspendServiceFunction(payload: String) = payload.uppercase()

@ServiceActivator(inputChannel = "flowServiceChannel", outputChannel = "resultChannel", async = "true")
fun flowServiceFunction(payload: String) =
    flow {
        for (i in 1..3) {
            emit("$payload #$i")
        }
    }

框架將它們視為反應式串流互動,並使用 ReactiveAdapterRegistry 轉換為各自的 MonoFlux reactor 類型。然後,如果回覆通道是 ReactiveStreamsSubscribableChannel,則會在回覆通道中處理此類函數回覆,或者作為各自回呼中 CompletableFuture 的結果。

具有 Flow 結果的函數在 @ServiceActivator 上預設不是 async,因此 Flow 實例會作為回覆訊息 Payload 產生。目標應用程式有責任將此物件作為協程處理,或分別將其轉換為 Flux

當在 Kotlin 中宣告時,@MessagingGateway 介面方法也可以使用 suspend 修飾符標記。框架在內部使用 Mono 來使用下游流程執行請求-回覆。此類 Mono 結果由內部的 MonoKt.awaitSingleOrNull() API 處理,以實現閘道器已呼叫 suspend 函數的 kotlin.coroutines.Continuation 引數

@MessagingGateway(defaultRequestChannel = "suspendRequestChannel")
interface SuspendFunGateway {

    suspend fun suspendGateway(payload: String): String

}

根據 Kotlin 語言要求,必須將此方法作為協程呼叫

@Autowired
private lateinit var suspendFunGateway: SuspendFunGateway

fun someServiceMethod() {
    runBlocking {
        val reply = suspendFunGateway.suspendGateway("test suspend gateway")
    }
}