camel-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Claus Ibsen (Confluence)" <conflue...@apache.org>
Subject [CONF] Apache Camel > Netty
Date Mon, 22 Jul 2013 09:14:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/en/2176/1/1/_/styles/combined.css?spaceKey=CAMEL&amp;forWysiwyg=true" type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/CAMEL/Netty">Netty</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~davsclaus">Claus Ibsen</a>
    </h4>
        <br/>
                         <h4>Changes (1)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >| {{bossPoll}} | {{null}} | *Camel 2.12:* To use a explicit {{org.jboss.netty.channel.socket.nio.BossPool}} as the boss thread pool. For example to share a thread pool with multiple consumers. By default each consumer has their own boss pool with 1 core thread. | <br>| {{workerPool}} | {{null}} | *Camel 2.12:* To use a explicit {{org.jboss.netty.channel.socket.nio.WorkerPool}} as the worker thread pool. For example to share a thread pool with multiple consumers. By default each consumer has their own worker pool with 2 x cpu count core threads. | <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">| {{networkInterface}} | {{null}} | *Camel 2.12:* Consumer only. When using UDP then this option can be used to specify a network interface by its name, such as {{eth0}} to join a multicast group. | <br></td></tr>
            <tr><td class="diff-unchanged" >{div} <br> <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <h2><a name="Netty-NettyComponent"></a>Netty Component</h2>
<p><b>Available as of Camel 2.3</b></p>

<p>The <b>netty</b> component in Camel is a socket communication component, based on the <a href="http://netty.io/" class="external-link" rel="nofollow">Netty</a> project.<br/>
Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients.<br/>
Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server.</p>

<p>This camel component supports both producer and consumer endpoints.</p>

<p>The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay etc) and facilitates both In-Only and In-Out communication on a Camel route.</p>

<p>Maven users will need to add the following dependency to their <tt>pom.xml</tt> for this component:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
&lt;dependency&gt;
    &lt;groupId&gt;org.apache.camel&lt;/groupId&gt;
    &lt;artifactId&gt;camel-netty&lt;/artifactId&gt;
    &lt;version&gt;x.x.x&lt;/version&gt;
    &lt;!-- use the same version as your Camel core version --&gt;
&lt;/dependency&gt;
</pre>
</div></div>

<h3><a name="Netty-URIformat"></a>URI format</h3>

<p>The URI scheme for a netty component is as follows</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
netty:tcp://localhost:99999[?options]
netty:udp://remotehost:99999/[?options]
</pre>
</div></div>

<p>This component supports producer and consumer endpoints for both TCP and UDP.</p>

<p>You can append query options to the URI in the following format, <tt>?option=value&amp;option=value&amp;...</tt></p>

<h3><a name="Netty-Options"></a>Options</h3>
<div class="confluenceTableSmall"><div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Name </th>
<th class='confluenceTh'> Default Value </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>keepAlive</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> Setting to ensure socket is not closed due to inactivity </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>tcpNoDelay</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> Setting to improve TCP protocol performance </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>backlog</tt> </td>
<td class='confluenceTd'>&nbsp;</td>
<td class='confluenceTd'> <b>Camel 2.9.6/2.10.4/2.11:</b> Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as <tt>200</tt>, <tt>500</tt> or <tt>1000</tt>, tells the TCP stack how long the "accept" queue can be. If this option is not configured, then the backlog depends on OS setting. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>broadcast</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> Setting to choose Multicast over UDP </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>connectTimeout</tt> </td>
<td class='confluenceTd'> <tt>10000</tt> </td>
<td class='confluenceTd'> Time to wait for a socket connection to be available. Value is in millis. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>reuseAddress</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> Setting to facilitate socket multiplexing </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>sync</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> Setting to set endpoint as one-way or request-response </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>synchronous</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10:</b> Whether <a href="/confluence/display/CAMEL/Asynchronous+Routing+Engine" title="Asynchronous Routing Engine">Asynchronous Routing Engine</a> is not in use. <tt>false</tt> then the <a href="/confluence/display/CAMEL/Asynchronous+Routing+Engine" title="Asynchronous Routing Engine">Asynchronous Routing Engine</a> is used, <tt>true</tt> to force processing synchronous. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>ssl</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> Setting to specify whether SSL encryption is applied to this endpoint </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>sslClientCertHeaders</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> When enabled and in SSL mode, then the Netty consumer will enrich the Camel <a href="/confluence/display/CAMEL/Message" title="Message">Message</a> with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>sendBufferSize</tt> </td>
<td class='confluenceTd'> <tt>65536 bytes</tt> </td>
<td class='confluenceTd'> The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>receiveBufferSize</tt> </td>
<td class='confluenceTd'> <tt>65536 bytes</tt> </td>
<td class='confluenceTd'> The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>option.XXX</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11/2.10.4:</b> Allows to configure additional netty options using "option." as prefix. For example "option.child.keepAlive=false" to set the netty option "child.keepAlive=false". See the Netty documentation for possible options that can be used. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>corePoolSize</tt> </td>
<td class='confluenceTd'> <tt>10</tt> </td>
<td class='confluenceTd'> The number of allocated threads at component startup. Defaults to 10. <b>Note:</b> This option is removed from Camel 2.9.2 onwards. As we rely on Nettys default settings. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>maxPoolSize</tt> </td>
<td class='confluenceTd'> <tt>100</tt> </td>
<td class='confluenceTd'> The maximum number of threads that may be allocated to this endpoint. Defaults to 100. <b>Note:</b> This option is removed from Camel 2.9.2 onwards. As we rely on Nettys default settings. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>disconnect</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>lazyChannelCreation</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>transferExchange</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>disconnectOnNoReply</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>noReplyLogLevel</tt> </td>
<td class='confluenceTd'> <tt>WARN</tt> </td>
<td class='confluenceTd'> If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. Values are: <tt>FATAL, ERROR, INFO, DEBUG, OFF</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>serverExceptionCaughtLogLevel</tt> </td>
<td class='confluenceTd'> <tt>WARN</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11.1:</b> If the server (NettyConsumer) catches an exception then its logged using this logging level. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>serverClosedChannelExceptionCaughtLogLevel</tt> </td>
<td class='confluenceTd'> <tt>DEBUG</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11.1:</b> If the server (NettyConsumer) catches an <tt>java.nio.channels.ClosedChannelException</tt> then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flod of closed exceptions in the Netty server. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>allowDefaultCodec</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> <b>Camel 2.4:</b> The netty component installs a default codec if both, encoder/deocder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>textline</tt> </td>
<td class='confluenceTd'> <tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.4:</b> Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>delimiter</tt> </td>
<td class='confluenceTd'> <tt>LINE</tt> </td>
<td class='confluenceTd'> <b>Camel 2.4:</b> The delimiter to use for the textline codec. Possible values are <tt>LINE</tt> and <tt>NULL</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>decoderMaxLineLength</tt> </td>
<td class='confluenceTd'> <tt>1024</tt> </td>
<td class='confluenceTd'> <b>Camel 2.4:</b> The max line length to use for the textline codec. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>autoAppendDelimiter</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> <b>Camel 2.4:</b> Whether or not to auto append missing end delimiter when sending using the textline codec. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>encoding</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.4:</b> The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>workerCount</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.9:</b> When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads*2. User can use this operation to override the default workerCount from Netty </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>sslContextParametersRef</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.9:</b> Reference to a <tt>org.apache.camel.util.jsse.SSLContextParameters</tt> in the <a href="/confluence/display/CAMEL/Registry" title="Registry">Registry</a>.&nbsp; This reference overrides any configured SSLContextParameters at the component level.&nbsp; See <a href="#Netty-UsingtheJSSEConfigurationUtility">Using the JSSE Configuration Utility</a>. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>receiveBufferSizePredictor</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.9:</b> Configures the buffer size predictor. See details at Jetty documentation and this <a href="http://lists.jboss.org/pipermail/netty-users/2010-January/001958.html" class="external-link" rel="nofollow">mail thread</a>. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>requestTimeout</tt> </td>
<td class='confluenceTd'> <tt>0</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11.1:</b> Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg <tt>30000</tt> is 30 seconds. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>needClientAuth</tt> </td>
<td class='confluenceTd'><tt>false</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11:</b> Configures whether the server needs client authentication when using SSL. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>orderedThreadPoolExecutor</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10.2:</b> Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. See details at the netty javadoc of <tt>org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor</tt> for more details. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>maximumPoolSize</tt> </td>
<td class='confluenceTd'> <tt>16</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10.2:</b> The core pool size for the ordered thread pool, if its in use. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>producerPoolEnabled</tt> </td>
<td class='confluenceTd'> <tt>true</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10.4/Camel 2.11:</b> Producer only. Whether producer pool is enabled or not. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>producerPoolMaxActive</tt> </td>
<td class='confluenceTd'> <tt>-1</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10.3:</b> Producer only. Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>producerPoolMinIdle</tt> </td>
<td class='confluenceTd'> <tt>0</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10.3:</b> Producer only. Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>producerPoolMaxIdle</tt> </td>
<td class='confluenceTd'> <tt>100</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10.3:</b> Producer only. Sets the cap on the number of "idle" instances in the pool. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>producerPoolMinEvictableIdle</tt> </td>
<td class='confluenceTd'> <tt>30000</tt> </td>
<td class='confluenceTd'> <b>Camel 2.10.3:</b> Producer only. Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>bootstrapConfiguration</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> Consumer only. Allows to configure the Netty ServerBootstrap options using a <tt>org.apache.camel.component.netty.NettyServerBootstrapConfiguration</tt> instance. This can be used to reuse the same configuration for multiple consumers, to align their configuration more easily. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>bossPoll</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> To use a explicit <tt>org.jboss.netty.channel.socket.nio.BossPool</tt> as the boss thread pool. For example to share a thread pool with multiple consumers. By default each consumer has their own boss pool with 1 core thread. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>workerPool</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> To use a explicit <tt>org.jboss.netty.channel.socket.nio.WorkerPool</tt> as the worker thread pool. For example to share a thread pool with multiple consumers. By default each consumer has their own worker pool with 2 x cpu count core threads. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>networkInterface</tt> </td>
<td class='confluenceTd'> <tt>null</tt> </td>
<td class='confluenceTd'> <b>Camel 2.12:</b> Consumer only. When using UDP then this option can be used to specify a network interface by its name, such as <tt>eth0</tt> to join a multicast group. </td>
</tr>
</tbody></table>
</div>
</div>

<h3><a name="Netty-RegistrybasedOptions"></a>Registry based Options</h3>

<p>Codec Handlers and SSL Keystores can be enlisted in the <a href="/confluence/display/CAMEL/Registry" title="Registry">Registry</a>, such as in the Spring XML file.<br/>
The values that could be passed in, are the following:</p>

<div class="confluenceTableSmall"><div class='table-wrap'>
<table class='confluenceTable'><tbody>
<tr>
<th class='confluenceTh'> Name </th>
<th class='confluenceTh'> Description </th>
</tr>
<tr>
<td class='confluenceTd'> <tt>passphrase</tt> </td>
<td class='confluenceTd'> password setting to use in order to encrypt/decrypt payloads sent using SSH </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>keyStoreFormat</tt> </td>
<td class='confluenceTd'> keystore format to be used for payload encryption. Defaults to "JKS" if not set </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>securityProvider</tt> </td>
<td class='confluenceTd'> Security provider to be used for payload encryption. Defaults to "SunX509" if not set. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>keyStoreFile</tt> </td>
<td class='confluenceTd'> <b>deprecated:</b> Client side certificate keystore to be used for encryption </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>trustStoreFile</tt> </td>
<td class='confluenceTd'> <b>deprecated:</b> Server side certificate keystore to be used for encryption </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>keyStoreResource</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11.1:</b> Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with <tt>"classpath:"</tt>, <tt>"file:"</tt>, or <tt>"http:"</tt> to load the resource from different systems. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>trustStoreResource</tt> </td>
<td class='confluenceTd'> <b>Camel 2.11.1:</b> Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with <tt>"classpath:"</tt>, <tt>"file:"</tt>, or <tt>"http:"</tt> to load the resource from different systems. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>sslHandler</tt> </td>
<td class='confluenceTd'> Reference to a class that could be used to return an SSL Handler </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>encoder</tt> </td>
<td class='confluenceTd'> A custom <tt>ChannelHandler</tt> class that can be used to perform special marshalling of outbound payloads. Must override <tt>org.jboss.netty.channel.ChannelDownStreamHandler</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>encorders</tt> </td>
<td class='confluenceTd'> A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the <a href="/confluence/display/CAMEL/Registry" title="Registry">Registry</a>. Just remember to prefix the value with # so Camel knows it should lookup. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>decoder</tt> </td>
<td class='confluenceTd'> A custom <tt>ChannelHandler</tt> class that can be used to perform special marshalling of inbound payloads. Must override <tt>org.jboss.netty.channel.ChannelUpStreamHandler</tt>. </td>
</tr>
<tr>
<td class='confluenceTd'> <tt>decoders</tt> </td>
<td class='confluenceTd'> A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the <a href="/confluence/display/CAMEL/Registry" title="Registry">Registry</a>. Just remember to prefix the value with # so Camel knows it should lookup. </td>
</tr>
</tbody></table>
</div>
</div>

<p><b>Important:</b> Read below about using non shareable encoders/decoders.</p>

<h4><a name="Netty-Usingnonshareableencodersordecoders"></a>Using non shareable encoders or decoders</h4>

<p>If your encoders or decoders is not shareable (eg they have the @Shareable class annotation), then your encoder/decoder must implement the <tt>org.apache.camel.component.netty.ChannelHandlerFactory</tt> interface, and return a new instance in the <tt>newChannelHandler</tt> method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when<br/>
an endpoint is created.</p>

<p>The Netty component offers a <tt>org.apache.camel.component.netty.ChannelHandlerFactories</tt> factory class, that has a number of commonly used methods.</p>

<h3><a name="Netty-SendingMessagesto%2FfromaNettyendpoint"></a>Sending Messages to/from a Netty endpoint</h3>

<h4><a name="Netty-NettyProducer"></a>Netty Producer</h4>

<p>In Producer mode, the component provides the ability to send payloads to a socket endpoint<br/>
using either TCP or UDP protocols (with optional SSL support).</p>

<p>The producer mode supports both one-way and request-response based operations.</p>

<h4><a name="Netty-NettyConsumer"></a>Netty Consumer</h4>

<p>In Consumer mode, the component provides the ability to:</p>
<ul class="alternate" type="square">
	<li>listen on a specified socket using either TCP or UDP protocols (with optional SSL support),</li>
	<li>receive requests on the socket using text/xml, binary and serialized object based payloads and</li>
	<li>send them along on a route as message exchanges.</li>
</ul>


<p>The consumer mode supports both one-way and request-response based operations.</p>

<h3><a name="Netty-UsageSamples"></a>Usage Samples</h3>

<h4><a name="Netty-AUDPNettyendpointusingRequestReplyandserializedobjectpayload"></a>A UDP Netty endpoint using Request-Reply and serialized object payload</h4>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
RouteBuilder builder = new RouteBuilder() {
  public void configure() {
    from("netty:udp://localhost:5155?sync=true")
      .process(new Processor() {
         public void process(Exchange exchange) throws Exception {
           Poetry poetry = (Poetry) exchange.getIn().getBody();
           poetry.setPoet("Dr. Sarojini Naidu");
           exchange.getOut().setBody(poetry);
         }
       }
    }
};
</pre>
</div></div>

<h4><a name="Netty-ATCPbasedNettyconsumerendpointusingOnewaycommunication"></a>A TCP based Netty consumer endpoint using One-way communication</h4>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
RouteBuilder builder = new RouteBuilder() {
  public void configure() {
       from("netty:tcp://localhost:5150")
           .to("mock:result");
  }
};
</pre>
</div></div>

<h4><a name="Netty-AnSSL%2FTCPbasedNettyconsumerendpointusingRequestReplycommunication"></a>An SSL/TCP based Netty consumer endpoint using Request-Reply communication</h4>

<h5><a name="Netty-UsingtheJSSEConfigurationUtility"></a>Using the JSSE Configuration Utility</h5>

<p>As of Camel 2.9, the Netty component supports SSL/TLS configuration through the <a href="/confluence/display/CAMEL/Camel+Configuration+Utilities" title="Camel Configuration Utilities">Camel JSSE Configuration Utility</a>.&nbsp;  This utility greatly decreases the amount of component specific code  you need to write and is configurable at the endpoint and component  levels.&nbsp; The following examples demonstrate how to use the utility with  the Netty component.</p>

<h6><a name="Netty-Programmaticconfigurationofthecomponent"></a>Programmatic configuration of the component</h6>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("/users/home/server/keystore.jks");
ksp.setPassword("keystorePassword");

KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyStore(ksp);
kmp.setKeyPassword("keyPassword");

SSLContextParameters scp = new SSLContextParameters();
scp.setKeyManagers(kmp);

NettyComponent nettyComponent = getContext().getComponent("netty", NettyComponent.class);
nettyComponent.setSslContextParameters(scp);
</pre>
</div></div>

<h6><a name="Netty-SpringDSLbasedconfigurationofendpoint"></a>Spring DSL based configuration of endpoint</h6>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
...
  &lt;camel:sslContextParameters
      id="sslContextParameters"&gt;
    &lt;camel:keyManagers
        keyPassword="keyPassword"&gt;
      &lt;camel:keyStore
          resource="/users/home/server/keystore.jks"
          password="keystorePassword"/&gt;
    &lt;/camel:keyManagers&gt;
  &lt;/camel:sslContextParameters&gt;...
...
  &lt;to uri="netty:tcp://localhost:5150?sync=true&amp;ssl=true&amp;sslContextParameters=#sslContextParameters"/&gt;
...
</pre>
</div></div>

<h5><a name="Netty-UsingBasicSSL%2FTLSconfigurationontheJettyComponent"></a>Using Basic SSL/TLS configuration on the Jetty Component</h5>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
JndiRegistry registry = new JndiRegistry(createJndiContext());
registry.bind("password", "changeit");
registry.bind("ksf", new File("src/test/resources/keystore.jks"));
registry.bind("tsf", new File("src/test/resources/keystore.jks"));

context.createRegistry(registry);
context.addRoutes(new RouteBuilder() {
  public void configure() {
      String netty_ssl_endpoint =
         "netty:tcp://localhost:5150?sync=true&amp;ssl=true&amp;passphrase=#password"
         + "&amp;keyStoreFile=#ksf&amp;trustStoreFile=#tsf";
      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);
          }
       }
  }
});
</pre>
</div></div>

<h5><a name="Netty-GettingaccesstoSSLSessionandtheclientcertificate"></a>Getting access to SSLSession and the client certificate</h5>
<p><b>Available as of Camel 2.12</b></p>

<p>You can get access to the <tt>javax.net.ssl.SSLSession</tt> if you eg need to get details about the client certificate. When <tt>ssl=true</tt> then the <a href="/confluence/display/CAMEL/Netty" title="Netty">Netty</a> component will store the <tt>SSLSession</tt> as a header on the Camel <a href="/confluence/display/CAMEL/Message" title="Message">Message</a> as shown below:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class);
// get the first certificate which is client certificate
javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0];
Principal principal = cert.getSubjectDN();
</pre>
</div></div>

<p>Remember to set <tt>needClientAuth=true</tt> to authenticate the client, otherwise <tt>SSLSession</tt> cannot access information about the client certificate, and you may get an exception <tt>javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated</tt>. You may also get this exception if the client certificate is expired or not valid etc.</p>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>The option <tt>sslClientCertHeaders</tt> can be set to <tt>true</tt> which then enriches the Camel <a href="/confluence/display/CAMEL/Message" title="Message">Message</a> with headers having details about the client certificate. For example the subject name is readily available in the header <tt>CamelNettySSLClientCertSubjectName</tt>.</td></tr></table></div>

<h4><a name="Netty-UsingMultipleCodecs"></a>Using Multiple Codecs</h4>

<p>In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (to lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the  pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param.</p>

<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>Read further above about using non shareable encoders/decoders.</td></tr></table></div>

<p>The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
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&lt;ChannelHandler&gt; decoders = new ArrayList&lt;ChannelHandler&gt;();
decoders.add(lengthDecoder);
decoders.add(stringDecoder);

List&lt;ChannelHandler&gt; encoders = new ArrayList&lt;ChannelHandler&gt;();
encoders.add(lengthEncoder);
encoders.add(stringEncoder);

registry.bind("encoders", encoders);
registry.bind("decoders", decoders);
]]></script>
</div></div>

<p>Spring's native collections support can be used to specify the codec lists in an application context</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
    &lt;util:list id="decoders" list-class="java.util.LinkedList"&gt;
        &lt;bean class="org.apache.camel.component.netty.ChannelHandlerFactories" factory-method="newLengthFieldBasedFrameDecoder"&gt;
            &lt;constructor-arg value="1048576"/&gt;
            &lt;constructor-arg value="0"/&gt;
            &lt;constructor-arg value="4"/&gt;
            &lt;constructor-arg value="0"/&gt;
            &lt;constructor-arg value="4"/&gt;
        &lt;/bean&gt;
        &lt;bean class="org.jboss.netty.handler.codec.string.StringDecoder"/&gt;
    &lt;/util:list&gt;

    &lt;util:list id="encoders" list-class="java.util.LinkedList"&gt;
        &lt;bean class="org.jboss.netty.handler.codec.frame.LengthFieldPrepender"&gt;
            &lt;constructor-arg value="4"/&gt;
        &lt;/bean&gt;
        &lt;bean class="org.jboss.netty.handler.codec.string.StringEncoder"/&gt;
    &lt;/util:list&gt;

    &lt;bean id="length-encoder" class="org.jboss.netty.handler.codec.frame.LengthFieldPrepender"&gt;
        &lt;constructor-arg value="4"/&gt;
    &lt;/bean&gt;
    &lt;bean id="string-encoder" class="org.jboss.netty.handler.codec.string.StringEncoder"/&gt;

    &lt;bean id="length-decoder" class="org.apache.camel.component.netty.ChannelHandlerFactories" factory-method="newLengthFieldBasedFrameDecoder"&gt;
        &lt;constructor-arg value="1048576"/&gt;
        &lt;constructor-arg value="0"/&gt;
        &lt;constructor-arg value="4"/&gt;
        &lt;constructor-arg value="0"/&gt;
        &lt;constructor-arg value="4"/&gt;
    &lt;/bean&gt;
    &lt;bean id="string-decoder" class="org.jboss.netty.handler.codec.string.StringDecoder"/&gt;

&lt;/beans&gt;
]]></script>
</div></div>

<p>The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: java; gutter: false"><![CDATA[
                from("direct:multiple-codec").to("netty:tcp://localhost:{{port}}?encoders=#encoders&amp;sync=false");
                
                from("netty:tcp://localhost:{{port}}?decoders=#length-decoder,#string-decoder&amp;sync=false").to("mock:multiple-codec");
            }
        };
    }
}
]]></script>
</div></div>

<p>or via spring.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<script type="syntaxhighlighter" class="theme: Default; brush: xml; gutter: false"><![CDATA[
&lt;camelContext id="multiple-netty-codecs-context" xmlns="http://camel.apache.org/schema/spring"&gt;
    &lt;route&gt;
        &lt;from uri="direct:multiple-codec"/&gt;
        &lt;to uri="netty:tcp://localhost:5150?encoders=#encoders&amp;amp;sync=false"/&gt;
    &lt;/route&gt;
    &lt;route&gt;
        &lt;from uri="netty:tcp://localhost:5150?decoders=#length-decoder,#string-decoder&amp;amp;sync=false"/&gt;
        &lt;to uri="mock:multiple-codec"/&gt;
    &lt;/route&gt;
&lt;/camelContext&gt;
]]></script>
</div></div>

<h3><a name="Netty-ClosingChannelWhenComplete"></a>Closing Channel When Complete</h3>

<p>When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished.<br/>
You can do this by simply setting the endpoint option <tt>disconnect=true</tt>.</p>

<p>However you can also instruct Camel on a per message basis as follows.<br/>
To instruct Camel to close the channel, you should add a header with the key <tt>CamelNettyCloseChannelWhenComplete</tt> set to a boolean <tt>true</tt> value.<br/>
For instance, the example below will close the channel after it has written the bye message back to the client:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
        from("netty:tcp://localhost:8080").process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                String body = exchange.getIn().getBody(String.class);
                exchange.getOut().setBody("Bye " + body);
                // some condition which determines if we should close
                if (close) {
                    exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
                }
            }
        });
</pre>
</div></div>

<h3><a name="Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline"></a>Adding custom channel pipeline factories to gain complete control over a created pipeline</h3>
<p><b>Available as of Camel 2.5</b></p>

<p>Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) &amp; decoders without having to specify them in the Netty Endpoint URL in a very simple way.</p>

<p>In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (JNDIRegistry,or the camel-spring ApplicationContextRegistry etc).</p>

<p>A custom pipeline factory must be constructed as follows</p>
<ul>
	<li>A Producer linked channel pipeline factory must extend the abstract class <tt>ClientPipelineFactory</tt>.</li>
	<li>A Consumer linked channel pipeline factory must extend the abstract class <tt>ServerPipelineFactory</tt>.</li>
	<li>The classes should override the getPipeline() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the getPipeline() method creates a pipeline with no handlers, encoders or decoders wired to the pipeline.</li>
</ul>


<p>The example below shows how ServerChannel Pipeline factory may be created</p>
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader" style="border-bottom-width: 1px;"><b>Using custom pipeline factory</b></div><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
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;
    }
}
</pre>
</div></div>

<p>The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: java; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
Registry registry = camelContext.getRegistry();
serverPipelineFactory = new TestServerChannelPipelineFactory();
registry.bind("spf", serverPipelineFactory);
context.addRoutes(new RouteBuilder() {
  public void configure() {
      String netty_ssl_endpoint =
         "netty:tcp://localhost: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);
          }
       }
  }
});

</pre>
</div></div>

<h3><a name="Netty-ReusingNettybossandworkerthreadpools"></a>Reusing Netty boss and worker thread pools</h3>
<p><b>Available as of Camel 2.12</b></p>

<p>Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the <a href="/confluence/display/CAMEL/Registry" title="Registry">Registry</a>.</p>

<p>For example using Spring XML we can create a shared worker thread pool using the <tt>NettyWorkerPoolBuilder</tt> with 2 worker threads as shown below:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
  &lt;!-- use the worker pool builder to create to help create the shared thread pool --&gt;
  &lt;bean id="poolBuilder" class="org.apache.camel.component.netty.NettyWorkerPoolBuilder"&gt;
    &lt;property name="workerCount" value="2"/&gt;
  &lt;/bean&gt;

  &lt;!-- the shared worker thread pool --&gt;
  &lt;bean id="sharedPool" class="org.jboss.netty.channel.socket.nio.WorkerPool"
        factory-bean="poolBuilder" factory-method="build" destroy-method="shutdown"&gt;
  &lt;/bean&gt;
</pre>
</div></div>

<div class='panelMacro'><table class='tipMacro'><colgroup><col width='24'><col></colgroup><tr><td valign='top'><img src="/confluence/images/icons/emoticons/check.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td><td>For boss thread pool there is a <tt>org.apache.camel.component.netty.NettyServerBossPoolBuilder</tt> builder for Netty consumers, and a <tt>org.apache.camel.component.netty.NettyClientBossPoolBuilder</tt> for the Netty produces.</td></tr></table></div>

<p>Then in the Camel routes we can refer to this worker pools by configuring the <tt>workerPool</tt> option in the <a href="/confluence/pages/createpage.action?spaceKey=CAMEL&amp;title=URI&amp;linkCreation=true&amp;fromPageId=14814487" class="createlink">URI</a> as shown below:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    &lt;route&gt;
      &lt;from uri="netty:tcp://localhost:5021?textline=true&amp;amp;sync=true&amp;amp;workerPool=#sharedPool&amp;amp;orderedThreadPoolExecutor=false"/&gt;
      &lt;to uri="log:result"/&gt;
      ...
    &lt;/route&gt;
</pre>
</div></div>

<p>And if we have another route we can refer to the shared worker pool:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="theme: Default; brush: xml; gutter: false" style="font-size:12px; font-family: ConfluenceInstalledFont,monospace;">
    &lt;route&gt;
      &lt;from uri="netty:tcp://localhost:5022?textline=true&amp;amp;sync=true&amp;amp;workerPool=#sharedPool&amp;amp;orderedThreadPoolExecutor=false"/&gt;
      &lt;to uri="log:result"/&gt;
      ...
    &lt;/route&gt;
</pre>
</div></div>
<p>... and so forth.</p>


<h3><a name="Netty-SeeAlso"></a>See Also</h3>
<ul>
	<li><a href="/confluence/display/CAMEL/Configuring+Camel" title="Configuring Camel">Configuring Camel</a></li>
	<li><a href="/confluence/display/CAMEL/Component" title="Component">Component</a></li>
	<li><a href="/confluence/display/CAMEL/Endpoint" title="Endpoint">Endpoint</a></li>
	<li><a href="/confluence/display/CAMEL/Getting+Started" title="Getting Started">Getting Started</a></li>
</ul>

<ul class="alternate" type="square">
	<li><a href="/confluence/display/CAMEL/Netty+HTTP" title="Netty HTTP">Netty HTTP</a></li>
	<li><a href="/confluence/display/CAMEL/MINA" title="MINA">MINA</a></li>
</ul>

    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;" class="grey">
                        <a href="https://cwiki.apache.org/confluence/users/removespacenotification.action?spaceKey=CAMEL">Stop watching space</a>
            <span style="padding: 0px 5px;">|</span>
                <a href="https://cwiki.apache.org/confluence/users/editmyemailsettings.action">Change email notification preferences</a>
</div>
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/Netty">View Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=14814487&revisedVersion=65&originalVersion=64">View Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/CAMEL/Netty?showComments=true&amp;showCommentArea=true#addcomment">Add Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message