首页 > 解决方案 > 服务器模式下的 Apache Camel netty4 生产者

问题描述

我在生产者模式下使用 Apache Camel netty4 组件,端点配置如下:

<from>
    <...>
</from>
<to>
    <endpoint:uriRouteEndpoint uri="netty4:tcp://127.0.0.1:12345"/>
</to>

当有消息要发送时,这里的 netty 端点充当 TCP 客户端,懒惰地启动到指定套接字的连接。

是否有一个简单的解决方案可以使其充当 TCP 服务器,即等到客户端软件启动并建立 TCP 连接后再发送消息?

标签: apache-camelnetty

解决方案


当然,这绝对可以通过Content Enricher EIP实现。您可以使用pollEnrich创建池化消费者等待输入。


我创建了用于演示的单元测试。

public class NettyEnrich extends CamelTestSupport {

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:in")
                        .pollEnrich("netty4:tcp://127.0.0.1:12345")
                        .to("mock:out");
            }
        };
    }

    @Test
    public void test() throws Exception{
        MockEndpoint mockEndpoint = getMockEndpoint("mock:out");
        mockEndpoint.setExpectedCount(1);

        template.asyncSendBody("direct:in",""); //direct:in is now waiting for connection from netty client
        template.sendBody("netty4:tcp://127.0.0.1:12345", "Hello from TCP"); //Initialize connection to resume direct:in

        mockEndpoint.assertIsSatisfied();
        Assert.assertEquals("Hello from TCP", mockEndpoint.getExchanges().get(0).getIn().getBody());
    }
}

推荐阅读