【问题标题】:Apache camel netty custom encoder and decoder sampleApache camel netty 自定义编码器和解码器示例
【发布时间】:2015-10-27 15:46:35
【问题描述】:

Apache camel netty tcp component doc(http://camel.apache.org/netty.html) 说,

编码器

A custom ChannelHandler class that can be used to perform special marshalling of outbound payloads. Must override org.jboss.netty.channel.ChannelDownStreamHandler.

解码器

A custom ChannelHandler class that can be used to perform special marshalling of inbound payloads. Must override org.jboss.netty.channel.ChannelUpStreamHandler.

您能否给我举个例子,说明如何/在重写类中做什么。我想要一个自定义的 tcp 编码器/解码器来读取/写入字节。

【问题讨论】:

    标签: java tcp apache-camel netty


    【解决方案1】:

    这个类和它的超类是编码器,你可以用它作为例子:org.jboss.netty.handler.codec.string.StringEncoder

    netty 页面上“使用多个编解码器”标题中的示例中使用了其他类,您可以查看源代码以了解它们如何使用接口。

    失败最好看看netty项目,看看编码器的单元测试。

    【讨论】:

    【解决方案2】:

    在 netty 文档中有使用 ChannelHandler 进行编码器和解码器的代码。来自文档:

    ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4);
    
    StringDecoder stringDecoder = new StringDecoder();
    registry.bind("length-decoder", lengthDecoder);
    registry.bind("string-decoder", stringDecoder);
    
    LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4);
    StringEncoder stringEncoder = new StringEncoder();
    registry.bind("length-encoder", lengthEncoder);
    registry.bind("string-encoder", stringEncoder);
    
    List<ChannelHandler> decoders = new ArrayList<ChannelHandler>();
    decoders.add(lengthDecoder);
    decoders.add(stringDecoder);
    
    List<ChannelHandler> encoders = new ArrayList<ChannelHandler>();
    encoders.add(lengthEncoder);
    encoders.add(stringEncoder);
    
    registry.bind("encoders", encoders);
    registry.bind("decoders", decoders);
    

    然后你指的是编码器/解码器:

    from("netty4:tcp://localhost:{{port}}?decoders=#length-decoder,#string-decoder&sync=false")
    

    我建议您先退后一步,使用 textline=true 和 allowDefaultCodec=false 运行您的 netty 流程,以查看您的 netty 通信是否正常。然后交给encoder/decoder部分。

    【讨论】:

      【解决方案3】:

      创建一个 SimpleRegistry 并将其传递给 CamelContext:

      SimpleRegistry simpleRegistry = new SimpleRegistry();
      simpleRegistry.put("stringEncoder", new StringEncoder());
      simpleRegistry.put("stringDecoder", new StringDecoder());
      CamelContext context = new DefaultCamelContext(simpleRegistry);
      

      【讨论】:

        猜你喜欢
        • 2018-04-12
        • 1970-01-01
        • 1970-01-01
        • 2020-06-27
        • 2017-10-19
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 2017-04-18
        相关资源
        最近更新 更多