该框架也得到了改进,以支持函数的 Kotlin lambda,因此现在您可以结合使用 Kotlin 语言和 Spring Integration 流定义:Spring中文文档

@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 协程的支持。 现在,函数和 & 返回类型可用于服务方法:suspendkotlinx.coroutines.Deferredkotlinx.coroutines.flow.FlowSpring中文文档

@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")
        }
    }

该框架将它们视为反应式流相互作用,并用于转换为相应的反应器类型。 这样的函数回复随后在回复通道中处理,如果它是 ,或者作为相应回调的结果。ReactiveAdapterRegistryMonoFluxReactiveStreamsSubscribableChannelCompletableFutureSpring中文文档

默认情况下,带有 result 的函数不在 上,因此实例将作为回复消息有效负载生成。 目标应用程序负责将此对象作为协程处理或分别将其转换为 。Flowasync@ServiceActivatorFlowFlux

在 Kotlin 中声明时,接口方法也可以用修饰符标记。 该框架在内部利用下游流执行请求-回复。 这样的结果由 API 在内部处理,以实现网关调用函数的参数:@MessagingGatewaysuspendMonoMonoMonoKt.awaitSingleOrNull()kotlin.coroutines.ContinuationsuspendSpring中文文档

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

    suspend fun suspendGateway(payload: String): String

}

此方法必须根据 Kotlin 语言要求作为协程调用:Spring中文文档

@Autowired
private lateinit var suspendFunGateway: SuspendFunGateway

fun someServiceMethod() {
    runBlocking {
        val reply = suspendFunGateway.suspendGateway("test suspend gateway")
    }
}
默认情况下,带有 result 的函数不在 上,因此实例将作为回复消息有效负载生成。 目标应用程序负责将此对象作为协程处理或分别将其转换为 。Flowasync@ServiceActivatorFlowFlux