239.9. 添加自定义频道管道工厂以获得对创建的管道的完整控制
可作为 Camel 2.5 提供
自定义频道管道通过插入自定义处理程序(s)、编码器和解码器(无需以 Netty Endpoint URL)来指定它们,可以在不需要以 Netty Endpoint URL 中指定它们,从而提供对处理程序/中断的链的完整控制。
要添加自定义管道,必须通过上下文 registry (JNDIRegistry,或 camel-spring ApplicationContextRegistry 等)使用上下文创建并注册自定义频道管道工厂。
必须按照以下方式构建自定义管道工厂:
-
与 Producer 链接的频道工厂必须扩展抽象类
ClientPipelineFactory。 -
Consumer 链接的频道管道工厂必须扩展抽象类
ServerPipelineFactory。 - 类应覆盖 getPipeline ()方法,以插入自定义处理程序、编码器和解码器。没有覆盖 getPipeline ()方法会创建一个没有处理程序、编码器或解码器线到管道的管道。
以下示例演示了如何创建 ServerChannel Pipeline 工厂
使用自定义管道工厂
public class SampleServerChannelPipelineFactory extends ServerPipelineFactory {
private int maxLineSize = 1024;
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline channelPipeline = Channels.pipeline();
channelPipeline.addLast("encoder-SD", new StringEncoder(CharsetUtil.UTF_8));
channelPipeline.addLast("decoder-DELIM", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter()));
channelPipeline.addLast("decoder-SD", new StringDecoder(CharsetUtil.UTF_8));
// here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc.
channelPipeline.addLast("handler", new ServerChannelHandler(consumer));
return channelPipeline;
}
}然后,自定义频道管道工厂可以添加到 registry 中,并按照以下方式在 camel 路由中实例化/使用
Registry registry = camelContext.getRegistry();
serverPipelineFactory = new TestServerChannelPipelineFactory();
registry.bind("spf", serverPipelineFactory);
context.addRoutes(new RouteBuilder() {
public void configure() {
String netty_ssl_endpoint =
"netty:tcp://0.0.0.0:5150?serverPipelineFactory=#spf"
String return_string =
"When You Go Home, Tell Them Of Us And Say,"
+ "For Your Tomorrow, We Gave Our Today.";
from(netty_ssl_endpoint)
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getOut().setBody(return_string);
}
}
}
});