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 的结果进行处理。
默认情况下,带有 Flow 结果的函数在 @ServiceActivator 上不是 async 的,因此 Flow 实例作为回复消息负载生成。目标应用程序负责将此对象作为协程处理或相应地将其转换为 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")
}
}