从Camel到Vertx套接字服务器的双向通信

时间:2014-09-06 09:35:53

标签: apache-camel netty vert.x

我正在尝试使用Camel NettyComponent与Vert.x中编写的SocketServer进行通信。

这是我的服务器代码:

public class NettyExampleServer {

    public final Vertx vertx;

    public static final Logger logger = LoggerFactory.getLogger(NettyExampleServer.class);

    public static int LISTENING_PORT = 15692;

    public NettyExampleServer(Vertx vertx) {
        this.vertx = vertx;
    }

    private NetServer netServer;

    private List<String> remoteAddresses = new CopyOnWriteArrayList<String>();
    private final AtomicInteger disconnections = new AtomicInteger();

    public int getDisconnections(){
        return disconnections.get();
    }

    public List<String> getRemoteAddresses(){
        return Collections.unmodifiableList(remoteAddresses);
    }

    public void run(){
        netServer = vertx.createNetServer();
        netServer.connectHandler(new Handler<NetSocket>() {
            @Override
            public void handle(final NetSocket socket) {
                remoteAddresses.add(socket.remoteAddress().toString());
                socket.closeHandler(new Handler<Void>() {
                    @Override
                    public void handle(Void event) {
                        disconnections.incrementAndGet();
                    }
                });
                socket.dataHandler(new Handler<Buffer>() {
                    @Override
                    public void handle(Buffer event) {
                        logger.info("I received {}",event);
                        socket.write("I am answering");
                    }
                });
            }
        });
        netServer.listen(LISTENING_PORT);



    }

    public void stop(){
        netServer.close();
    }
}

我尝试构建如下路线:

public class NettyRouteBuilder extends RouteBuilder {

    public static final String PRODUCER_BUS_NAME = "producerBus";
    public static final String CONSUMER_BUS_NAME = "receiverBus";

    private Processor processor = new Processor(){
        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.setPattern(ExchangePattern.InOut);
        }
    };

    @Override
    public void configure() throws Exception {
        from("vertx:" + PRODUCER_BUS_NAME).process(processor).to("netty:tcp://localhost:"+ NettyExampleServer.LISTENING_PORT + "?textline=true&lazyChannelCreation=true&option.child.keepAlive=true").to("vertx:"+CONSUMER_BUS_NAME);

    }
}

我的测试表明:

  • 如果我删除路由上的处理器,则传递成功,但服务器没有应答
  • 如果我保留处理器,数据会传送到服务器,但由于没有收到数据而引发异常。

我在这里创建了一个小项目:https://github.com/edmondo1984/netty-camel-vertx。如何使用Camel Netty Component创建双向路由?

1 个答案:

答案 0 :(得分:0)

要传达Vertx和Camel,最好的工具就是使用以下方法之一:

您可以找到示例here

如果您可以或者有其他要求,也可以在双方使用像Netty这样的通用连接器。