Paho
| Deprecated: This paho is deprecated and may be removed in a future release. |
Since Camel 2.16
Both producer and consumer are supported
Paho component provides a connector for the MQTT messaging protocol using the Eclipse Paho library. Paho is one of the most popular MQTT libraries, so if you would like to integrate it with your Java project - Camel Paho connector is a way to go.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-paho</artifactId>
<version>x.y.z</version>
<!-- use the same version as your Camel core version -->
</dependency> Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Paho component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Whether the client reconnects to the broker by itself when the connection is lost. It waits 1 second before the first attempt, and the wait doubles after each failed attempt while it is below maxReconnectDelay. After a reconnect the consumer subscribes to its topic again. A failure of the first connect, when the consumer or producer starts, is not retried. | true | boolean | |
The URI of the MQTT broker: tcp:// for MQTT over TCP, ssl:// for MQTT over TLS, ws:// for MQTT over WebSocket or wss:// for MQTT over secure WebSocket, for example tcp://localhost:1883. Without a port, the client uses 1883 for tcp://, 8883 for ssl://, 80 for ws:// and 443 for wss://. When serverURIs is set, the client connects to those URIs instead. | tcp://localhost:1883 | String | |
The MQTT clean session flag. When true, the broker discards the session of the client identifier when the client connects, and the session lasts only as long as the connection; the consumer unsubscribes from the topic when it stops. When false, the broker keeps the subscriptions of the client identifier and queues the QoS 1 and QoS 2 messages for it while the client is offline, and delivers them when a client with the same identifier connects again; this needs a fixed clientId, and the consumer does not unsubscribe when it stops. | true | boolean | |
The MQTT client identifier that the client sends to the broker when it connects. When it is not set, each consumer and producer generates an identifier (camel-paho followed by a number) that changes with every start. The broker allows one connection per client identifier and disconnects the older one, so give each consumer and producer its own identifier. A fixed identifier is needed to resume a session that the broker kept (cleanSession=false). | String | ||
The shared configuration that each endpoint copies its options from. The options of the endpoint URI override the copied values. | PahoConfiguration | ||
The maximum time in seconds that the client waits to open the network connection to the broker: the TCP connect, and also the TLS handshake for ssl:// and wss://. 0 means no timeout: the client waits until the connection succeeds or fails. A negative value fails the start. | 30 | int | |
The base directory of the FILE persistence. The client stores its messages in a subdirectory named after the client identifier and the broker URI. When not set, the working directory of the JVM (the user.dir system property) is used. Not used with MEMORY persistence. | String | ||
The MQTT keep alive interval in seconds: the longest time between two control packets that the client sends. When the client has sent nothing else in this time, it sends a PINGREQ, and the broker disconnects a client that it hears nothing from in one and a half times this interval. 0 turns keep alive off. A negative value fails the start. | 60 | int | |
The maximum number of messages that the client publishes at the same time: a QoS 0 message counts until it is written to the network, a QoS 1 or QoS 2 message until the broker acknowledges it. When the limit is reached, publishing a message fails with an MqttException (reason code 32202, too many publishes in progress). Increase it when many threads send to the producer at the same time. 0 makes every publish fail. | 10 | int | |
The limit in milliseconds of the wait between two automatic reconnect attempts. The wait starts at 1 second and doubles after each failed attempt while it is below this limit, so it stops growing at the first value that reaches or passes the limit (with the default, at 128 seconds). Used only when automaticReconnect is true. | 128000 | int | |
The MQTT protocol version: 0 connects with MQTT 3.1.1 and falls back to MQTT 3.1 when that connect fails, 4 uses only MQTT 3.1.1 and 3 uses only MQTT 3.1. Any other value fails the start. | int | ||
Where the client stores its QoS 1 and QoS 2 messages that are in flight, so that it can complete their delivery after a reconnect. MEMORY keeps them in memory, so they are lost when the client stops. FILE stores them in files below filePersistenceDirectory, so that a client with the same client identifier can complete them after a restart, when cleanSession is false (a clean session clears them on connect). Enum values:
| MEMORY | PahoPersistence | |
The MQTT quality of service (QoS) level: 0 (at most once), 1 (at least once) or 2 (exactly once). The consumer subscribes to the topic with this QoS, which is the highest QoS with which the broker delivers messages to it. The producer publishes messages with this QoS, unless the CamelPahoQos header sets another one. | 2 | int | |
Whether the producer publishes messages as retained messages: the broker keeps the last retained message of a topic and sends it to each client that subscribes to the topic later. The CamelPahoRetained header overrides this option for a message. | false | boolean | |
A comma-separated list of broker URIs (in the format of brokerUrl, without spaces) that the client connects to instead of brokerUrl. The client tries them in order and connects to the first one that accepts the connection; the connect fails when none does. Use it for brokers that share their session state (high availability; set cleanSession to false for durable subscriptions), or for independent brokers to try in turn (set cleanSession to true, as their state is not shared). | String | ||
The payload of the will message (Last Will and Testament), as text that is converted to bytes with the default charset of the JVM. The will message is set only when willTopic is set too. | String | ||
The QoS level (0, 1 or 2) with which the broker publishes the will message. | int | ||
Whether the broker publishes the will message as a retained message. | false | boolean | |
The topic of the will message (Last Will and Testament), which the broker publishes when the connection of the client ends without a DISCONNECT, for example when the network fails or the keep alive times out. It cannot contain wildcards. The will message is set only when willPayload is set too. | String | ||
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
Whether the consumer acknowledges each QoS 1 and QoS 2 message itself when the exchange completes successfully, instead of the Paho client acknowledging it when the message callback returns. When the exchange fails, the message is not acknowledged, and the broker sends it again only when the client reconnects to a session that the broker kept (cleanSession=false). With a client set by the client option, the consumer does not switch that client to manual acknowledgements: set that on the client itself. | false | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
A shared org.eclipse.paho.client.mqttv3.MqttClient, already connected, that the consumers and producers of all endpoints use instead of creating their own clients. Camel does not connect, disconnect or close this client, and does not apply the connection options to it, such as brokerUrl, clientId, persistence, keepAliveInterval, automaticReconnect, the will and the security options. | MqttClient | ||
Extra HTTP headers that the client sends in the WebSocket opening handshake of ws:// and wss:// connections. Not used for tcp:// and ssl://. | Properties | ||
The time in seconds that the Paho client waits for its executor service to terminate when it shuts down. It has no effect: the Paho client version that this component uses never shuts down an executor service with it, and the clients that the component creates have no executor service. | 1 | int | |
Whether the client verifies, in the TLS handshake of ssl:// and wss:// connections, that the certificate of the broker matches the host name of the broker URI, as HTTPS does. When false, the client verifies the host name with sslHostnameVerifier if that is set, and otherwise not at all. | true | boolean | |
The password for authentication with the MQTT broker. It is sent only when the userName option is set too. | String | ||
A custom javax.net.SocketFactory that the client uses to create its network sockets. For ssl:// and wss:// broker URIs it must be a javax.net.ssl.SSLSocketFactory, and the sslClientProps option is then not used. For tcp:// and ws:// it must not be an SSLSocketFactory. A factory of the wrong type fails the connect. | SocketFactory | ||
The TLS settings for ssl:// and wss:// connections, as Paho SSL properties from which the client creates its SSLSocketFactory. Not used when the socketFactory option is set. The keys are com.ibm.ssl.protocol (TLS when not set), com.ibm.ssl.contextProvider, com.ibm.ssl.keyStore, com.ibm.ssl.keyStorePassword, com.ibm.ssl.keyStoreType, com.ibm.ssl.keyStoreProvider, com.ibm.ssl.keyManager, com.ibm.ssl.trustStore, com.ibm.ssl.trustStorePassword, com.ibm.ssl.trustStoreType, com.ibm.ssl.trustStoreProvider, com.ibm.ssl.trustManager, com.ibm.ssl.enabledCipherSuites (a comma-separated list) and com.ibm.ssl.clientAuthentication. Any other key fails the connect. A key store or trust store that is not set falls back to the javax.net.ssl system properties of the JVM. | Properties | ||
A custom javax.net.ssl.HostnameVerifier for ssl:// and wss:// connections. It is used only when httpsHostnameVerificationEnabled is false: after the TLS handshake the client calls it with the host name of the broker URI, and closes the connection with an SSLPeerUnverifiedException when it returns false. | HostnameVerifier | ||
The user name for authentication with the MQTT broker. It is sent only when the password option is set too. | String |
Endpoint Options
The Paho endpoint is configured using URI syntax:
paho:topic
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The MQTT topic. The consumer subscribes to it as a topic filter, which can contain the wildcards + (one topic level) and # (all remaining levels). The producer publishes to it as a topic name, which cannot contain wildcards, unless the CamelPahoOverrideTopic header sets another topic. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Whether the client reconnects to the broker by itself when the connection is lost. It waits 1 second before the first attempt, and the wait doubles after each failed attempt while it is below maxReconnectDelay. After a reconnect the consumer subscribes to its topic again. A failure of the first connect, when the consumer or producer starts, is not retried. | true | boolean | |
The URI of the MQTT broker: tcp:// for MQTT over TCP, ssl:// for MQTT over TLS, ws:// for MQTT over WebSocket or wss:// for MQTT over secure WebSocket, for example tcp://localhost:1883. Without a port, the client uses 1883 for tcp://, 8883 for ssl://, 80 for ws:// and 443 for wss://. When serverURIs is set, the client connects to those URIs instead. | tcp://localhost:1883 | String | |
The MQTT clean session flag. When true, the broker discards the session of the client identifier when the client connects, and the session lasts only as long as the connection; the consumer unsubscribes from the topic when it stops. When false, the broker keeps the subscriptions of the client identifier and queues the QoS 1 and QoS 2 messages for it while the client is offline, and delivers them when a client with the same identifier connects again; this needs a fixed clientId, and the consumer does not unsubscribe when it stops. | true | boolean | |
The MQTT client identifier that the client sends to the broker when it connects. When it is not set, each consumer and producer generates an identifier (camel-paho followed by a number) that changes with every start. The broker allows one connection per client identifier and disconnects the older one, so give each consumer and producer its own identifier. A fixed identifier is needed to resume a session that the broker kept (cleanSession=false). | String | ||
The maximum time in seconds that the client waits to open the network connection to the broker: the TCP connect, and also the TLS handshake for ssl:// and wss://. 0 means no timeout: the client waits until the connection succeeds or fails. A negative value fails the start. | 30 | int | |
The base directory of the FILE persistence. The client stores its messages in a subdirectory named after the client identifier and the broker URI. When not set, the working directory of the JVM (the user.dir system property) is used. Not used with MEMORY persistence. | String | ||
The MQTT keep alive interval in seconds: the longest time between two control packets that the client sends. When the client has sent nothing else in this time, it sends a PINGREQ, and the broker disconnects a client that it hears nothing from in one and a half times this interval. 0 turns keep alive off. A negative value fails the start. | 60 | int | |
The maximum number of messages that the client publishes at the same time: a QoS 0 message counts until it is written to the network, a QoS 1 or QoS 2 message until the broker acknowledges it. When the limit is reached, publishing a message fails with an MqttException (reason code 32202, too many publishes in progress). Increase it when many threads send to the producer at the same time. 0 makes every publish fail. | 10 | int | |
The limit in milliseconds of the wait between two automatic reconnect attempts. The wait starts at 1 second and doubles after each failed attempt while it is below this limit, so it stops growing at the first value that reaches or passes the limit (with the default, at 128 seconds). Used only when automaticReconnect is true. | 128000 | int | |
The MQTT protocol version: 0 connects with MQTT 3.1.1 and falls back to MQTT 3.1 when that connect fails, 4 uses only MQTT 3.1.1 and 3 uses only MQTT 3.1. Any other value fails the start. | int | ||
Where the client stores its QoS 1 and QoS 2 messages that are in flight, so that it can complete their delivery after a reconnect. MEMORY keeps them in memory, so they are lost when the client stops. FILE stores them in files below filePersistenceDirectory, so that a client with the same client identifier can complete them after a restart, when cleanSession is false (a clean session clears them on connect). Enum values:
| MEMORY | PahoPersistence | |
The MQTT quality of service (QoS) level: 0 (at most once), 1 (at least once) or 2 (exactly once). The consumer subscribes to the topic with this QoS, which is the highest QoS with which the broker delivers messages to it. The producer publishes messages with this QoS, unless the CamelPahoQos header sets another one. | 2 | int | |
Whether the producer publishes messages as retained messages: the broker keeps the last retained message of a topic and sends it to each client that subscribes to the topic later. The CamelPahoRetained header overrides this option for a message. | false | boolean | |
A comma-separated list of broker URIs (in the format of brokerUrl, without spaces) that the client connects to instead of brokerUrl. The client tries them in order and connects to the first one that accepts the connection; the connect fails when none does. Use it for brokers that share their session state (high availability; set cleanSession to false for durable subscriptions), or for independent brokers to try in turn (set cleanSession to true, as their state is not shared). | String | ||
The payload of the will message (Last Will and Testament), as text that is converted to bytes with the default charset of the JVM. The will message is set only when willTopic is set too. | String | ||
The QoS level (0, 1 or 2) with which the broker publishes the will message. | int | ||
Whether the broker publishes the will message as a retained message. | false | boolean | |
The topic of the will message (Last Will and Testament), which the broker publishes when the connection of the client ends without a DISCONNECT, for example when the network fails or the keep alive times out. It cannot contain wildcards. The will message is set only when willPayload is set too. | String | ||
Whether the consumer acknowledges each QoS 1 and QoS 2 message itself when the exchange completes successfully, instead of the Paho client acknowledging it when the message callback returns. When the exchange fails, the message is not acknowledged, and the broker sends it again only when the client reconnects to a session that the broker kept (cleanSession=false). With a client set by the client option, the consumer does not switch that client to manual acknowledgements: set that on the client itself. | false | boolean | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
An existing org.eclipse.paho.client.mqttv3.MqttClient, already connected, that the consumer and producer of this endpoint use instead of creating their own client. Camel does not connect, disconnect or close this client, and does not apply the connection options to it, such as brokerUrl, clientId, persistence, keepAliveInterval, automaticReconnect, the will and the security options. | MqttClient | ||
Extra HTTP headers that the client sends in the WebSocket opening handshake of ws:// and wss:// connections. Not used for tcp:// and ssl://. | Properties | ||
The time in seconds that the Paho client waits for its executor service to terminate when it shuts down. It has no effect: the Paho client version that this component uses never shuts down an executor service with it, and the clients that the component creates have no executor service. | 1 | int | |
Whether the client verifies, in the TLS handshake of ssl:// and wss:// connections, that the certificate of the broker matches the host name of the broker URI, as HTTPS does. When false, the client verifies the host name with sslHostnameVerifier if that is set, and otherwise not at all. | true | boolean | |
The password for authentication with the MQTT broker. It is sent only when the userName option is set too. | String | ||
A custom javax.net.SocketFactory that the client uses to create its network sockets. For ssl:// and wss:// broker URIs it must be a javax.net.ssl.SSLSocketFactory, and the sslClientProps option is then not used. For tcp:// and ws:// it must not be an SSLSocketFactory. A factory of the wrong type fails the connect. | SocketFactory | ||
The TLS settings for ssl:// and wss:// connections, as Paho SSL properties from which the client creates its SSLSocketFactory. Not used when the socketFactory option is set. The keys are com.ibm.ssl.protocol (TLS when not set), com.ibm.ssl.contextProvider, com.ibm.ssl.keyStore, com.ibm.ssl.keyStorePassword, com.ibm.ssl.keyStoreType, com.ibm.ssl.keyStoreProvider, com.ibm.ssl.keyManager, com.ibm.ssl.trustStore, com.ibm.ssl.trustStorePassword, com.ibm.ssl.trustStoreType, com.ibm.ssl.trustStoreProvider, com.ibm.ssl.trustManager, com.ibm.ssl.enabledCipherSuites (a comma-separated list) and com.ibm.ssl.clientAuthentication. Any other key fails the connect. A key store or trust store that is not set falls back to the javax.net.ssl system properties of the JVM. | Properties | ||
A custom javax.net.ssl.HostnameVerifier for ssl:// and wss:// connections. It is used only when httpsHostnameVerificationEnabled is false: after the TLS handshake the client calls it with the host name of the broker URI, and closes the connection with an SSLPeerUnverifiedException when it returns false. | HostnameVerifier | ||
The user name for authentication with the MQTT broker. It is sent only when the password option is set too. | String |
Message Headers
The Paho component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The name of the topic that the message was published to (with a wildcard subscription, the topic of the message, not the topic filter). | String | |
| Constant: | The QoS level (0, 1 or 2) with which the broker delivered the message: the lower of the QoS of the publisher and the QoS of the subscription. | Integer | |
| Constant: | The QoS level (0, 1 or 2) to publish the message with, instead of the qos option. | Integer | |
| Constant: | Whether to publish the message as a retained message, instead of the retained option. | Boolean | |
CamelPahoOverrideTopic (producer) Constant: | The topic to publish the message to, instead of the topic of the endpoint. | String |
Message Body
The message body at each side of the Paho component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The payload of the MQTT message. |
Producer input |
| What converts to a byte array: text, bytes, a stream or a file, sent as the payload. A Map, a POJO or no body fails: marshal it first. |
Producer output |
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Usage
Default payload type
By default, the Camel Paho component operates on the binary payloads extracted out of (or put into) the MQTT message:
// Receive payload
byte[] payload = (byte[]) consumerTemplate.receiveBody("paho:topic");
// Send payload
byte[] payload = "message".getBytes();
producerTemplate.sendBody("paho:topic", payload); Of course, Camel built-in type conversion API can perform the automatic data type transformations for you. In the example below Camel automatically converts binary payload into String (and conversely):
// Receive payload
String payload = consumerTemplate.receiveBody("paho:topic", String.class);
// Send payload
String payload = "message";
producerTemplate.sendBody("paho:topic", payload); Examples
For example, the following snippet reads messages from the MQTT broker installed on the same host as the Camel router:
-
Java
-
XML
-
YAML
from("paho:some/queue")
.to("mock:test"); <route>
<from uri="paho:some/queue"/>
<to uri="mock:test"/>
</route> - route:
from:
uri: paho:some/queue
steps:
- to:
uri: mock:test While the snippet below sends a message to the MQTT broker:
-
Java
-
XML
-
YAML
from("direct:test")
.to("paho:some/target/queue"); <route>
<from uri="direct:test"/>
<to uri="paho:some/target/queue"/>
</route> - route:
from:
uri: direct:test
steps:
- to:
uri: paho:some/target/queue For example, this is how to read messages from the remote MQTT broker:
-
Java
-
XML
-
YAML
from("paho:some/queue?brokerUrl=tcp://iot.eclipse.org:1883")
.to("mock:test"); <route>
<from uri="paho:some/queue?brokerUrl=tcp://iot.eclipse.org:1883"/>
<to uri="mock:test"/>
</route> - route:
from:
uri: paho:some/queue
parameters:
brokerUrl: "tcp://iot.eclipse.org:1883"
steps:
- to:
uri: mock:test And here we override the default topic and set to a dynamic topic
-
Java
-
XML
-
YAML
from("direct:test")
.setHeader("CamelPahoOverrideTopic", simple("${header.customerId}"))
.to("paho:some/target/queue"); <route>
<from uri="direct:test"/>
<setHeader name="CamelPahoOverrideTopic">
<simple>${header.customerId}</simple>
</setHeader>
<to uri="paho:some/target/queue"/>
</route> - route:
from:
uri: direct:test
steps:
- setHeader:
name: CamelPahoOverrideTopic
simple: "${header.customerId}"
- to:
uri: paho:some/target/queue