如何在Java中实现集成路由器

时间:2018-08-27 16:32:44

标签: spring-integration

我正在尝试将下面的XML代码段转换为Java版本,在此感谢任何帮助

<int:router input-channel="channel_in" default-output-channel="channel_default" 
  expression="payload.name" ignore-channel-name-resolution-failures="true">
    <int:mapping value="foo" channel="channel_one" />
    <int:mapping value="bar" channel="channel_two" />
</int:router>

这是我为具体示例所做的

@Router(inputChannel = "routerChannel")
    public String route(Account message) {
        if (message.getType().equals("check")) {
            return "checkChannel";
        } else if (message.getType().equals("credit")) {
            return "creditChannel";
        } 
        return "errorChannel";
}

@Bean
public DirectChannel checkChannel() {
    return new DirectChannel();
}

当我在上面做时,我看到下面的错误

org.springframework.messaging.MessageDeliveryException:调度程序没有频道“ application:8090.checkChannel”的订阅者。

1 个答案:

答案 0 :(得分:1)

所有Spring Integration自定义标记都具有如下描述:

<xsd:element name="router" type="routerType">
    <xsd:annotation>
        <xsd:documentation>
            Defines a Consumer Endpoint for the
            'org.springframework.integration.router.AbstractMessageProcessingRouter' implementation
            that serves as an adapter for invoking a method on any
            Spring-managed object as specified by the "ref" and "method" attributes.
        </xsd:documentation>
    </xsd:annotation>
</xsd:element>

因此,很明显,我们需要在Java配置中提供一些AbstractMessageProcessingRouter实现。

我们在参考手册中还有一个段落,如this

  

借助XML配置和Spring Integration命名空间支持,XML解析器隐藏了如何声明目标bean并将它们连接在一起。对于Java和注释配置,重要的是要了解面向目标最终用户应用程序的Framework API。

根据您的expression="payload.name",我们需要查找ExpressionEvaluatingRouter,然后阅读有关@Bean configuration的一章:

    @Bean
    @Router(inputChannel = "channel_in")
    public ExpressionEvaluatingRouter expressionRouter() {
        ExpressionEvaluatingRouter router = new ExpressionEvaluatingRouter("payload.name");
        router.setDefaultOutputChannelName("channel_default");
        router.setChannelMapping("foo", "channel_one");
        router.setChannelMapping("bar", "channel_two");
        return router;
    }