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")
}
}
框架将它们视为 Reactive Streams 交互,并使用 ReactiveAdapterRegistry 将其转换为相应的 Mono 和 Flux reactor 类型。
然后,此类函数回复在回复通道中进行处理(如果它是 ReactiveStreamsSubscribableChannel),或者作为 CompletableFuture 的结果在相应的回调中进行处理。
|
默认情况下,带有 |
当在 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")
}
}