Kotlin 中基于消息头的 Spring Integration DSL 路由

问题描述 投票:0回答:1

我的消息包含字符串,我想根据标头路由消息,如下所示:

            .route<Message<String?>, String> {
                when (it.headers["routing_header"] as Int) {
                    1 -> "channel_1"
                    2 -> "channel_2"
                    else -> "nullChannel"
                }
            }

在这种情况下,我在转换字符串时出错

原因:java.lang.ClassCastException:类java.lang.String无法转换为类org.springframework.messaging.Message

我的路由出了什么问题?

java kotlin spring-integration spring-integration-dsl
1个回答
0
投票

您必须研究专用的 Spring Integration Kotlin DSL:https://docs.spring.io/spring-integration/reference/kotlin-dsl.html

route
可以这样配置:

                route<Message<String?>> {
                    when (it.headers["routing_header"] as Int?) {
                        1 -> "channel_1"
                        2 -> "channel_2"
                        else -> "nullChannel"
                    }
                }

请注意

Int?
的修复,因为您的标头可能会丢失,并将作为
null
返回。

如果你仍然对 Kotlin 中的 Java DSL 组合感到厌烦,那么修复方法可能是这样的:

                        .route(Message::class.java) {
                            when (it.headers["routing_header"] as Int?) {
                                1 -> "channel_1"
                                2 -> "channel_2"
                                else -> "nullChannel"
                            }
                        }

Java 会进行泛型擦除,因此我们不知道

Message
在运行时的类型期望。因此,Java 变体需要我们显式地输入该类型,而 Kotlin 变体需要具体化类型。

© www.soinside.com 2019 - 2024. All rights reserved.