Paho MQTT 5
Since Camel 3.8
Both producer and consumer are supported
Paho MQTT5 component provides connector for the MQTT messaging protocol version 5.0 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-mqtt5</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 MQTT 5 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 5 Clean Start flag. When true, the broker discards any existing session of the client identifier when the client connects and starts a new one, the client clears its stored in-flight messages, and the consumer unsubscribes from the topic when it stops. When false, the broker resumes the session of the client identifier, if it still has one, with its subscriptions and the QoS 1 and QoS 2 messages queued while the client was offline, and the consumer does not unsubscribe when it stops. How long the broker keeps a session after the connection closes is set by sessionExpiryInterval, and by default the session ends with the connection: a durable subscription needs cleanStart=false, a sessionExpiryInterval greater than 0 and a fixed clientId. | 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 random UUID) 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 (cleanStart=false and a sessionExpiryInterval greater than 0). | String | ||
The shared configuration that each endpoint copies its options from. The options of the endpoint URI override the copied values. | PahoMqtt5Configuration | ||
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. 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. The broker can return another value (Server Keep Alive) when the client connects, which the client then uses. 0 turns keep alive off. A negative value fails the start. | 60 | 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). The consumer also uses it as the limit of the wait before it reconnects after a failed exchange with manualAcksEnabled. | 128000 | 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 cleanStart is false (a clean start clears them on connect). Enum values:
| MEMORY | PahoMqtt5Persistence | |
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 CamelPahoMqtt5Qos header sets another one. | 2 | int | |
The MQTT 5 Receive Maximum that the client sends when it connects: the most QoS 1 and QoS 2 messages that the broker sends to the client without having received their acknowledgement. QoS 0 messages are not limited. With manualAcksEnabled, the messages that are still being routed count against this limit. It must be between 1 and 65535, otherwise the start fails. | 65535 | 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 CamelPahoMqtt5Retained 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 cleanStart to false for durable subscriptions), or for independent brokers to try in turn (set cleanStart to true, as their state is not shared). | String | ||
The MQTT 5 Session Expiry Interval in seconds that the client sends when it connects: how long the broker keeps the session (the subscriptions and the queued QoS 1 and QoS 2 messages) after the network connection closes. A negative value, the default, does not send it, and the broker then uses 0. 0 ends the session when the connection closes, and 4294967295 keeps it without expiry. A value above 4294967295 fails the connect. The broker can return a shorter interval. Set cleanStart to false to resume the session when the client connects again. | -1 | long | |
The MQTT 5 properties of the will message (an org.eclipse.paho.mqttv5.common.packet.MqttProperties), such as the Will Delay Interval, the Message Expiry Interval, the Content Type or user properties. They are not sent to the broker: the component sets them on the will message, while the Paho client sends only the will properties of its connection options, so the broker publishes the will message without them. | MqttProperties | ||
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. | 1 | 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 normal 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, instead of the Paho client acknowledging it when the message callback returns. The Paho client holds back only the acknowledgement of a QoS 1 message; it completes the QoS 2 flow on its own. When the exchange of a QoS 1 message fails on a session that the broker keeps (cleanStart=false and a sessionExpiryInterval greater than 0), the consumer connects again so that the broker sends the message again (a client set by the client option is not connected again: the message stays unacknowledged until that client connects again). In all other cases the broker would not send it again, so the failed message is acknowledged. 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.mqttv5.client.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://. | Map | ||
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 does not read it. | 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 host name is verified only by sslHostnameVerifier, if that is set. | 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. 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. It is called also when httpsHostnameVerificationEnabled is true, in addition to that check. | HostnameVerifier | ||
The user name for authentication with the MQTT broker. | String |
Endpoint Options
The Paho MQTT 5 endpoint is configured using URI syntax:
paho-mqtt5: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), or name a shared subscription ($share/, the share name and a topic filter, for example $share/group1/sensors/+). The producer publishes to it as a topic name, which cannot contain wildcards, unless the CamelPahoMqtt5OverrideTopic 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 5 Clean Start flag. When true, the broker discards any existing session of the client identifier when the client connects and starts a new one, the client clears its stored in-flight messages, and the consumer unsubscribes from the topic when it stops. When false, the broker resumes the session of the client identifier, if it still has one, with its subscriptions and the QoS 1 and QoS 2 messages queued while the client was offline, and the consumer does not unsubscribe when it stops. How long the broker keeps a session after the connection closes is set by sessionExpiryInterval, and by default the session ends with the connection: a durable subscription needs cleanStart=false, a sessionExpiryInterval greater than 0 and a fixed clientId. | 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 random UUID) 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 (cleanStart=false and a sessionExpiryInterval greater than 0). | 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. 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. The broker can return another value (Server Keep Alive) when the client connects, which the client then uses. 0 turns keep alive off. A negative value fails the start. | 60 | 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). The consumer also uses it as the limit of the wait before it reconnects after a failed exchange with manualAcksEnabled. | 128000 | 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 cleanStart is false (a clean start clears them on connect). Enum values:
| MEMORY | PahoMqtt5Persistence | |
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 CamelPahoMqtt5Qos header sets another one. | 2 | int | |
The MQTT 5 Receive Maximum that the client sends when it connects: the most QoS 1 and QoS 2 messages that the broker sends to the client without having received their acknowledgement. QoS 0 messages are not limited. With manualAcksEnabled, the messages that are still being routed count against this limit. It must be between 1 and 65535, otherwise the start fails. | 65535 | 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 CamelPahoMqtt5Retained 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 cleanStart to false for durable subscriptions), or for independent brokers to try in turn (set cleanStart to true, as their state is not shared). | String | ||
The MQTT 5 Session Expiry Interval in seconds that the client sends when it connects: how long the broker keeps the session (the subscriptions and the queued QoS 1 and QoS 2 messages) after the network connection closes. A negative value, the default, does not send it, and the broker then uses 0. 0 ends the session when the connection closes, and 4294967295 keeps it without expiry. A value above 4294967295 fails the connect. The broker can return a shorter interval. Set cleanStart to false to resume the session when the client connects again. | -1 | long | |
The MQTT 5 properties of the will message (an org.eclipse.paho.mqttv5.common.packet.MqttProperties), such as the Will Delay Interval, the Message Expiry Interval, the Content Type or user properties. They are not sent to the broker: the component sets them on the will message, while the Paho client sends only the will properties of its connection options, so the broker publishes the will message without them. | MqttProperties | ||
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. | 1 | 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 normal 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, instead of the Paho client acknowledging it when the message callback returns. The Paho client holds back only the acknowledgement of a QoS 1 message; it completes the QoS 2 flow on its own. When the exchange of a QoS 1 message fails on a session that the broker keeps (cleanStart=false and a sessionExpiryInterval greater than 0), the consumer connects again so that the broker sends the message again (a client set by the client option is not connected again: the message stays unacknowledged until that client connects again). In all other cases the broker would not send it again, so the failed message is acknowledged. 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.mqttv5.client.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://. | Map | ||
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 does not read it. | 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 host name is verified only by sslHostnameVerifier, if that is set. | 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. 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. It is called also when httpsHostnameVerificationEnabled is true, in addition to that check. | HostnameVerifier | ||
The user name for authentication with the MQTT broker. | String |
Message Headers
The Paho MQTT 5 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 or shared 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 | |
CamelPahoMqtt5Retained (producer) Constant: | Whether to publish the message as a retained message, instead of the retained option. | Boolean | |
CamelPahoMqtt5OverrideTopic (producer) Constant: | The topic to publish the message to, instead of the topic of the endpoint. | String | |
CamelPahoMqtt5MsgProperties (common) Constant: | Consumer: The properties set on the incoming message. Producer: The publish properties (not the topic alias, which the client assigns) copied into each published message. | MqttProperties |
Message Body
The message body at each side of the Paho MQTT 5 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.
Deterministic simulation tests
The consumer of the Paho MQTT 5 component is tested with deterministic simulation tests: the real consumer runs under a seeded virtual-time scheduler against a fake of the external system, which injects faults while the tests check invariants. A failing seed can be replayed. These are the fake worlds of the component:
| World | What it checks | Issues |
|---|---|---|
Fake: FakeMqtt: an MQTT 5 broker with the session of the client id (Clean Start, Session Expiry, Receive Maximum, resend on reconnect) and a Paho MqttClient subclass on it, given to the consumer by a test component Tests: | Covers:
Faults:
Invariants:
|
The worlds and their tests are in the test sources of the component. How to run them, replay a seed and write a world is described in Running the tests and Writing a fake world.
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-mqtt5:topic");
// Send payload
byte[] payload = "message".getBytes();
producerTemplate.sendBody("paho-mqtt5: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-mqtt5:topic", String.class);
// Send payload
String payload = "message";
producerTemplate.sendBody("paho-mqtt5:topic", payload); Manual acknowledgements
With manualAcksEnabled=true a message is acknowledged when its exchange completes. MQTT has no negative acknowledgement: the broker sends an unacknowledged message again only when the client connects again to a session that the broker kept, and it does not send more than receiveMaximum unacknowledged messages to the client. The client holds back only the acknowledgement of a QoS 1 message; it completes the QoS 2 flow on its own when the message arrives, so the broker never sends a QoS 2 message again. So when an exchange fails:
-
for a QoS 1 message on a session that the broker keeps after the disconnect (
cleanStart=falseandsessionExpiryIntervalgreater than 0) the consumer disconnects and connects again, and the broker sends the message again; -
in all other cases (a clean session, which is the default, a QoS 2 message, or
cleanStart=falsewithoutsessionExpiryInterval, where the session ends with the connection) the broker never sends the message again, so the consumer acknowledges it, and the failure is left to the Camel error handler; -
with a client set by the
clientoption, a QoS 1 message on a session that the broker keeps stays unacknowledged until that client connects again. The consumer does not connect that client, so it tells the cases apart with thecleanStartandsessionExpiryIntervalof the endpoint: set them to match the connection options of the client. With the defaults (a clean session) a failed message is acknowledged.
The reconnects of failed exchanges in a row back off: the first one waits one second, each further one waits twice as long, up to maxReconnectDelay (but at least one second), and any exchange that succeeds, also one of another message, starts again from one second. So on a topic where other messages succeed in between, a message that always fails makes the consumer reconnect about once a second. Each such reconnect is logged at WARN. The consumer closes its client and connects a new one with the same client id, which resumes the session, so getClient() of the consumer returns another instance afterwards. The broker then also sends again the other QoS 1 messages that were not acknowledged yet, such as the ones still being routed: those are not acknowledged when their exchange completes, as their client is closed, so such a message is routed twice, the second time possibly while its first exchange is still running. A message that always fails is still delivered again and again; use a Camel error handler, for example a dead letter channel, for such messages.
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-mqtt5:some/queue")
.to("mock:test"); <route>
<from uri="paho-mqtt5:some/queue"/>
<to uri="mock:test"/>
</route> - route:
from:
uri: paho-mqtt5: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-mqtt5:some/target/queue"); <route>
<from uri="direct:test"/>
<to uri="paho-mqtt5:some/target/queue"/>
</route> - route:
from:
uri: direct:test
steps:
- to:
uri: paho-mqtt5:some/target/queue For example, this is how to read messages from the remote MQTT broker:
-
Java
-
XML
-
YAML
from("paho-mqtt5:some/queue?brokerUrl=tcp://iot.eclipse.org:1883")
.to("mock:test"); <route>
<from uri="paho-mqtt5:some/queue?brokerUrl=tcp://iot.eclipse.org:1883"/>
<to uri="mock:test"/>
</route> - route:
from:
uri: paho-mqtt5: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-mqtt5:some/target/queue"); <route>
<from uri="direct:test"/>
<setHeader name="CamelPahoMqtt5OverrideTopic">
<simple>${header.customerId}</simple>
</setHeader>
<to uri="paho-mqtt5:some/target/queue"/>
</route> - route:
from:
uri: direct:test
steps:
- setHeader:
name: CamelPahoMqtt5OverrideTopic
simple: "${header.customerId}"
- to:
uri: paho-mqtt5:some/target/queue