Camel Components

Simple JMS

Since Camel 2.11

Both producer and consumer are supported

The Simple JMS Component is a JMS component that only uses JMS APIs and no third-party framework such as Spring JMS.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-sjms</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

sjms:[queue:|topic:]destinationName[?options]

Where destinationName is a JMS queue or topic name. By default, the destinationName is interpreted as a queue name. For example, to connect to the queue, FOO.BAR use:

sjms:FOO.BAR

You can include the optional queue: prefix, if you prefer:

sjms:queue:FOO.BAR

To connect to a topic, you must include the topic: prefix. For example, to connect to the topic, Stocks.Prices, use:

sjms:topic:Stocks.Prices

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, *.yaml files, 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 Simple JMS component supports the following options which are listed below.

Name Description Default Type

clientId (common)

The JMS client ID that the consumers set on their JMS connection (Connection.setClientID), for the endpoints that do not set their own. The JMS provider allows a client ID on one connection at a time, so set it on the component only when it has a single consumer endpoint. A durable topic subscription that is not shared needs it. A request/reply producer sets it, with the suffix .CamelReplyManager, on the connection of its reply consumer.

String

connectionFactory (common)

Autowired The JMS ConnectionFactory that creates the JMS connections; set it on the component or on the endpoint. The producer opens and closes a connection for each message it sends, so use a pooling ConnectionFactory for producers.

ConnectionFactory

bridgeErrorHandler (consumer)

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

lazyStartProducer (producer)

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

autowiredEnabled (advanced)

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

destinationCreationStrategy (advanced)

A custom DestinationCreationStrategy that creates the jakarta.jms.Destination for a destination name, and the temporary queue for the replies of request/reply. The default calls Session.createQueue, Session.createTopic or Session.createTemporaryQueue.

DestinationCreationStrategy

exceptionListener (advanced)

A jakarta.jms.ExceptionListener that the consumer (and the reply consumer of a request/reply producer) notifies when its JMS connection fails, or when a JMSException occurs while it handles a message. The consumer reconnects by itself (see recoveryInterval).

ExceptionListener

jmsKeyFormatStrategy (advanced)

The strategy that encodes the names of Camel headers into names that JMS allows for message properties when sending, and decodes them when receiving. The default replaces a dot with DOT and a hyphen with HYPHEN, and back. Refer to a custom org.apache.camel.component.sjms.jms.JmsKeyFormatStrategy with the # notation. The endpoints do not use the value set on the component: set it on the endpoint.

JmsKeyFormatStrategy

messageCreatedStrategy (advanced)

A MessageCreatedStrategy that Camel calls each time it creates a jakarta.jms.Message to send (also for the replies of the consumer), to change the message before it is sent.

MessageCreatedStrategy

objectMessageEnabled (advanced)

Whether to enable sending and receiving JMS ObjectMessage. By default this is disabled because Java object serialization is a known source of security vulnerabilities. Enable this option only if you trust the source of the messages and need to send or receive Java serialized objects via JMS. When disabled, Camel will refuse to create or read JMS ObjectMessage instances. Options that rely on ObjectMessage internally (such as transferException) require this option to be enabled.

false

boolean

recoveryInterval (advanced)

The time in millis between the attempts of the consumer (and of the reply consumer of a request/reply producer) to reconnect after its JMS connection failed. The first attempt is made 1 second after the failure, and the attempts go on until one succeeds or the consumer stops.

5000

long

replyToOnTimeoutMaxConcurrentConsumers (advanced)

The maximum number of threads, per request/reply (InOut) producer, that continue routing the exchanges whose reply did not arrive within the requestTimeout (they continue with an ExchangeTimedOutException). Must be at least 1.

1

int

requestTimeoutCheckerInterval (advanced)

How often, in millis, a request/reply (InOut) producer checks for requests whose requestTimeout has passed, and fails them with an ExchangeTimedOutException. Lower it to react sooner to a timeout.

1000

long

headerFilterStrategy (filter)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message.

HeaderFilterStrategy

deserializationFilter (security)

Sets an ObjectInputFilter pattern (jdk.serialFilter syntax) applied as a defense-in-depth check on the class of the body returned by jakarta.jms.ObjectMessage.getObject(). The pattern is evaluated after the JMS provider has deserialized the payload, so this option alone does not prevent gadget-chain execution that happens inside the provider’s ObjectInputStream; to block such attacks, also configure the JMS provider’s own deserialization filter and/or the JVM-wide -Djdk.serialFilter. When this option is not set and no JVM-wide filter is configured, a conservative default filter denying java.net. and otherwise allowing java., javax. and org.apache.camel. is applied.

String

Endpoint Options

The Simple JMS endpoint is configured using URI syntax:

sjms:destinationType:destinationName

With the following path and query parameters:

Path Parameters

Name Description Default Type

destinationType (common)

Whether destinationName is a queue (the default) or a topic, given as a prefix of the destination name, such as queue:orders or topic:prices.

Enum values:

  • queue

  • topic

queue

String

destinationName (common)

Required The name of the JMS queue or topic to send to or receive from. It is a queue unless destinationType is topic.

String

Query Parameters

Name Description Default Type

acknowledgementMode (common)

The acknowledge mode of the JMS sessions of the consumer, and of a producer that sends without expecting a reply (InOnly). AUTO_ACKNOWLEDGE: the session acknowledges each message, also when its exchange failed. CLIENT_ACKNOWLEDGE: Camel acknowledges the message after its exchange has been routed, or recovers the session when the exchange failed, so the message is delivered again. DUPS_OK_ACKNOWLEDGE: the session acknowledges lazily, so a message may be delivered twice. For a transacted session use transacted=true, which sets SESSION_TRANSACTED. A request/reply (InOut) producer and its reply consumer always use AUTO_ACKNOWLEDGE.

Enum values:

  • SESSION_TRANSACTED

  • CLIENT_ACKNOWLEDGE

  • AUTO_ACKNOWLEDGE

  • DUPS_OK_ACKNOWLEDGE

AUTO_ACKNOWLEDGE

SessionAcknowledgementType

connectionFactory (common)

The JMS ConnectionFactory that creates the JMS connections; set it on the component or on the endpoint. The producer opens and closes a connection for each message it sends, so use a pooling ConnectionFactory for producers.

ConnectionFactory

disableReplyTo (common)

Whether to ignore reply-to. The consumer sends no reply, neither to the JMSReplyTo of a received message nor to replyTo. The producer sends an exchange that expects a reply (InOut) as a one-way message, without JMSReplyTo, and does not wait for a reply. Use it when another system sends the reply, or to move messages from one broker to another.

false

boolean

replyTo (common)

The name of a queue for the replies of request/reply. On the producer, Camel sets it as the JMSReplyTo of each request and receives the replies from it, instead of from a temporary queue. Only this producer should consume from the queue (see replyToType), so give each producer its own queue. Setting it makes the endpoint use the InOut exchange pattern. On the consumer, Camel sends the reply of every received message to this destination, instead of to the JMSReplyTo of the message.

String

testConnectionOnStartup (common)

Whether the consumer and the producer open (and close) a JMS connection when they start, so that Camel fails to start when the JMS broker cannot be reached, instead of starting with a consumer or producer that fails later.

false

boolean

asyncConsumer (consumer)

Whether the consumer lets the asynchronous routing engine continue an exchange, and receives the next message before that exchange is done. A message may then be acknowledged before its exchange is done, and messages may be processed out of order. By default each exchange is routed fully before the next message is received. Not used when transacted or synchronous is enabled.

false

boolean

autoStartup (consumer)

Whether the consumer starts its listener container (its JMS connection, sessions and MessageConsumers) when the consumer starts. When false, the consumer receives no messages until the listener container is started from Java with SjmsConsumer.startListenerContainer().

true

boolean

clientId (consumer)

The JMS client ID that the consumer sets on its JMS connection (Connection.setClientID). The JMS provider allows a client ID on one connection at a time, so each consumer endpoint needs its own (the sessions of concurrentConsumers share the connection). A durable topic subscription that is not shared needs it. A request/reply producer sets it, with the suffix .CamelReplyManager, on the connection of its reply consumer.

String

concurrentConsumers (consumer)

The number of JMS sessions, each with its own MessageConsumer, that the consumer opens on its JMS connection to receive and route messages in parallel. Fixed when the consumer starts. With batching, each session collects its own batches. On a topic, use more than 1 only with a shared subscription (sjms2), as each MessageConsumer of a subscription that is not shared receives every message. A request/reply producer uses replyToConcurrentConsumers for its replies.

1

int

durableSubscriptionName (consumer)

The name of the durable subscription that the consumer creates on the topic, so the JMS provider keeps its messages while the consumer is offline. A durable subscription that is not shared is identified by this name together with the clientId, so clientId must be set too. Not used for a queue.

String

replyToDeliveryPersistent (consumer)

Not used: the replies that the consumer sends get the delivery mode of deliveryPersistent and deliveryMode.

true

boolean

bridgeErrorHandler (consumer (advanced))

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

eagerLoadingOfProperties (consumer (advanced))

Whether the consumer reads the body and the JMS properties of each message when it receives it, instead of when the route first uses them. This costs time when the route does not use them, but finds a message that cannot be read before it is routed (see eagerPoisonBody).

false

boolean

eagerPoisonBody (consumer (advanced))

With eagerLoadingOfProperties, the body to give the exchange of a message whose body or JMS properties cannot be read (a poison message), so the route can still handle it; the exception is set on the exchange. A Simple expression. Set to false to turn this off, so such a message fails.

Poison JMS message payload: ${exception.message}

String

exceptionHandler (consumer (advanced))

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

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

messageSelector (consumer (advanced))

A JMS message selector, a condition in SQL-92 syntax on the JMS headers and properties of a message (such as JMSPriority > 4 AND region = 'EU'), that selects the messages the consumer receives. Also used when pollEnrich or a ConsumerTemplate receives from the endpoint. Not used for the replies of request/reply.

String

replyToSameDestinationAllowed (consumer (advanced))

Whether the consumer may send a reply to the destination it consumes from, when the JMSReplyTo of a message is its JMSDestination. By default no reply is sent then, to avoid an endless loop of the consumer receiving its own replies.

false

boolean

deliveryMode (producer)

The JMS delivery mode of the messages that the producer sends: 1 (NON_PERSISTENT) or 2 (PERSISTENT), as defined by jakarta.jms.DeliveryMode. Takes precedence over deliveryPersistent, and is also used for the replies that the consumer sends. Setting it turns explicitQosEnabled on, unless that is set to false.

Enum values:

  • 1

  • 2

Integer

deliveryPersistent (producer)

Whether the producer sends messages with the PERSISTENT delivery mode (true) or the NON_PERSISTENT one (false). deliveryMode takes precedence. Also used for the replies that the consumer sends. Setting it turns explicitQosEnabled on, unless that is set to false.

true

boolean

priority (producer)

The JMS priority of the messages that the producer sends, from 1 to 9, where 9 is the highest (the JMS default is 4). Setting it turns explicitQosEnabled on, unless that is set to false.

Enum values:

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

4

int

replyToConcurrentConsumers (producer)

The number of JMS sessions, each with its own MessageConsumer, that a request/reply (InOut) producer uses to receive the replies from its reply queue.

1

int

replyToOverride (producer)

The destination to set as JMSReplyTo of the messages that the producer sends, instead of the queue that Camel receives the replies on (InOut), or the JMSReplyTo header (InOnly). A queue: or topic: prefix selects the type of destination; without a prefix it is that of the endpoint. For request/reply, Camel still waits for the reply on its own reply queue, so use it when another system forwards the reply to that queue.

String

replyToType (producer)

The kind of queue that a request/reply (InOut) producer receives its replies on: Temporary, a temporary queue that the producer creates, or Exclusive, the queue named by replyTo, which only this producer consumes from. The kind follows from replyTo: without replyTo a temporary queue is used, and Temporary together with replyTo fails.

Enum values:

  • Temporary

  • Exclusive

ReplyToType

requestTimeout (producer)

The time in millis that a request/reply (InOut) producer waits for the reply; the exchange then fails with an ExchangeTimedOutException. The CamelJmsRequestTimeout header overrides it per message. It is also the time to live of the request message, unless timeToLive is set or disableTimeToLive is enabled. The component option requestTimeoutCheckerInterval sets how often the timeouts are checked.

20000

long

timeToLive (producer)

The time to live in millis of the messages that the producer sends: the JMS provider discards a message that is not delivered within this time. -1 (the default) or 0 means that the messages do not expire. For request/reply (InOut) it takes precedence over requestTimeout as the time to live of the request. Also used for the replies that the consumer sends. Setting it turns explicitQosEnabled on, unless that is set to false.

-1

long

allowNullBody (producer (advanced))

Whether the producer may send a message with a null body, as a JMS message without a body. When false, a null body fails with a JMSException.

true

boolean

disableTimeToLive (producer (advanced))

For request/reply (InOut): whether to send the request without the time to live that Camel otherwise sets from requestTimeout, so that the request does not expire on the broker when the clocks of the sender and the receiver differ. A timeToLive that is set still applies.

false

boolean

explicitQosEnabled (producer (advanced))

Whether the producer sends each message with the deliveryMode (or deliveryPersistent), priority and timeToLive of the endpoint, instead of the defaults of the JMS provider. Setting one of those options turns this option on, unless it is set to false. preserveMessageQos, by contrast, takes these values from the headers of each message. Also keeps the JMSReplyTo of a message that is sent without expecting a reply (InOnly).

false

Boolean

lazyStartProducer (producer (advanced))

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

preserveMessageQos (producer (advanced))

Whether the producer takes the delivery mode, priority and expiration of each message from its JMSDeliveryMode, JMSPriority and JMSExpiration headers (JMSExpiration is the time in millis since the epoch at which the message expires). A missing header falls back to the deliveryMode (or deliveryPersistent), priority and timeToLive of the endpoint. Also keeps the JMSReplyTo of a message that is sent without expecting a reply (InOnly).

false

boolean

asyncStartListener (advanced)

Whether the consumer starts its listener container (its JMS connection, sessions and MessageConsumers) on a separate thread, so the route starts without waiting for the JMS broker. If the listener container fails to start, the error is logged at WARN level, and the consumer receives no messages until the route is restarted.

false

boolean

asyncStopListener (advanced)

Whether the consumer stops its listener container (its JMS connection, sessions and MessageConsumers) on a separate thread, so stopping the route does not wait for it.

false

boolean

destinationCreationStrategy (advanced)

A custom DestinationCreationStrategy that creates the jakarta.jms.Destination for a destination name, and the temporary queue for the replies of request/reply. The default calls Session.createQueue, Session.createTopic or Session.createTemporaryQueue.

DestinationCreationStrategy

exceptionListener (advanced)

A jakarta.jms.ExceptionListener that the consumer (and the reply consumer of a request/reply producer) notifies when its JMS connection fails, or when a JMSException occurs while it handles a message. The consumer reconnects by itself (see recoveryInterval).

ExceptionListener

headerFilterStrategy (advanced)

A custom HeaderFilterStrategy that decides which Camel headers are sent as JMS properties, and which JMS properties of a received message become Camel headers. It replaces the default strategy, so includeAllJMSXProperties is then not used.

HeaderFilterStrategy

includeAllJMSXProperties (advanced)

Whether to also send the JMSX headers of the Camel message that the JMS provider sets itself (JMSXUserID, JMSXAppID, JMSXDeliveryCount, JMSXProducerTXID, JMSXConsumerTXID, JMSXRcvTimestamp, JMSXRecvTimestamp and JMSXState) as JMS properties of the messages that the producer sends (and of the replies of the consumer). By default they are not sent. The headers of a received message are not affected. Not used when headerFilterStrategy is set.

false

boolean

jmsKeyFormatStrategy (advanced)

The strategy that encodes the names of Camel headers into names that JMS allows for message properties when sending, and decodes them when receiving. The default replaces a dot with DOT and a hyphen with HYPHEN, and back. Refer to a custom org.apache.camel.component.sjms.jms.JmsKeyFormatStrategy with the # notation.

JmsKeyFormatStrategy

jmsMessageType (advanced)

The type of JMS message to send, instead of the type that Camel chooses from the body: Bytes, Map, Object, Stream or Text. Camel converts the body to what the message type needs. Object needs objectMessageEnabled. Also used for the replies that the consumer sends.

Enum values:

  • Bytes

  • Map

  • Object

  • Stream

  • Text

JmsMessageType

mapJmsMessage (advanced)

Whether Camel maps the body of a received JMS message to a Java type: a TextMessage to a String, a BytesMessage to a byte array, a MapMessage to a Map, a StreamMessage to an InputStream, and an ObjectMessage (with objectMessageEnabled) to its object. When false, the body is the jakarta.jms.Message itself.

true

boolean

messageCreatedStrategy (advanced)

A MessageCreatedStrategy that Camel calls each time it creates a jakarta.jms.Message to send (also for the replies of the consumer), to change the message before it is sent.

MessageCreatedStrategy

objectMessageEnabled (advanced)

Whether to enable sending and receiving JMS ObjectMessage. By default this is disabled because Java object serialization is a known source of security vulnerabilities. Enable this option only if you trust the source of the messages and need to send or receive Java serialized objects via JMS. When disabled, Camel will refuse to create or read JMS ObjectMessage instances. Options that rely on ObjectMessage internally (such as transferException) require this option to be enabled.

false

boolean

recoveryInterval (advanced)

The time in millis between the attempts of the consumer (and of the reply consumer of a request/reply producer) to reconnect after its JMS connection failed. The first attempt is made 1 second after the failure, and the attempts go on until one succeeds or the consumer stops.

5000

long

synchronous (advanced)

Whether to process strictly synchronously: the producer completes each send, and waits for the reply of request/reply, on the calling thread, and the consumer routes each exchange fully before it receives the next message, even with asyncConsumer.

false

boolean

transferException (advanced)

For request/reply (InOut): whether the consumer sends the exception of a failed exchange back as the reply, in a JMS ObjectMessage, and the producer, when it receives such a reply, sets the exception on its exchange, so the caller fails with it. The exception must be Serializable, and both sides need objectMessageEnabled. Without it, a failed exchange gets no reply, and the caller fails when its requestTimeout has passed. Java serialization couples the producer and the consumer to the same exception classes.

false

boolean

batching (batch)

Enable batch consuming. The route receives one Exchange per batch, whose body is a list of Exchange objects, one for each JMS message, instead of one Exchange per message.

false

boolean

batchInterval (batch)

Time in millis, measured from the first message received into a new batch, after which the batch is dispatched even if batchSize has not been reached, comparable to the Aggregator EIP’s completionInterval. Default is 1000 ms, that is 1 second. Set to 0 to disable the interval, so a batch is only dispatched when batchSize is reached (not recommended).

1000

long

batchSize (batch)

Maximum number of messages per batch.

100

int

deserializationFilter (security)

Sets an ObjectInputFilter pattern (jdk.serialFilter syntax) applied as a defense-in-depth check on the class of the body returned by jakarta.jms.ObjectMessage.getObject(). The pattern is evaluated after the JMS provider has deserialized the payload, so this option alone does not prevent gadget-chain execution that happens inside the provider’s ObjectInputStream; to block such attacks, also configure the JMS provider’s own deserialization filter and/or the JVM-wide -Djdk.serialFilter. When this option is not set and no JVM-wide filter is configured, a conservative default filter denying java.net. and otherwise allowing java., javax. and org.apache.camel. is applied.

String

transacted (transaction)

Whether the consumer and the producer use a transacted JMS session (a local transaction), which sets acknowledgementMode to SESSION_TRANSACTED. The consumer commits the session after the exchange has been routed, or rolls it back when the exchange failed, so the JMS provider delivers the message again. The producer commits or rolls back its session when the exchange completes. A producer cannot be both transacted and InOut, and a transacted consumer always routes synchronously.

false

boolean

Message Headers

The Simple JMS component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelJMSDestinationName (producer)

Constant: JMS_DESTINATION_NAME

The name of the queue or topic to send the message to, instead of the destinationName of the endpoint. It is a queue or a topic as the endpoint is. The producer removes the header from the message.

String

CamelJmsRequestTimeout (producer)

Constant: JMS_REQUEST_TIMEOUT

The time in millis that the producer waits for the reply of this request/reply (InOut) message, instead of the requestTimeout of the endpoint.

long

JMSCorrelationID (producer)

Constant: JMS_CORRELATION_ID

The JMSCorrelationID of the message. The producer sets it on the message it sends; for request/reply (InOut) without this header, Camel generates one, and matches the reply by it. The consumer sets the header from the received message, and gives its reply the JMSCorrelationID of the request (or its JMSMessageID when it has none).

String

JMSReplyTo (producer)

Constant: JMS_REPLY_TO

The reply-to destination (a jakarta.jms.Destination, or a name where a queue: or topic: prefix selects the type) to set as JMSReplyTo of a message that the producer sends without expecting a reply (InOnly). It is kept only with preserveMessageQos or explicitQosEnabled, and replyToOverride takes precedence. For request/reply (InOut), Camel sets JMSReplyTo to the queue it receives the reply on. The consumer sets the header to the JMSReplyTo of the received message.

String

CamelSjmsBatchSize (batch)

Constant: SJMS_BATCH_SIZE_HEADER

The number of messages in the batch, which is the size of the list in the body, set by the consumer when batching is enabled.

int

Message Body

The message body at each side of the Simple JMS 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

text, bytes, map, stream or null

By the JMS message received: a String for a TextMessage, a byte array for a BytesMessage, a Map for a MapMessage, an InputStream for a StreamMessage, and null for a plain Message. An ObjectMessage fails unless objectMessageEnabled.

  • With mapJmsMessage=false: pojo (jakarta.jms.Message)

  • With objectMessageEnabled=true: text, bytes, map, stream, value, list, pojo or null

Consumer reply

text, bytes, stream, file, map or null

The reply, sent as the producer sends a message. A reply that cannot be sent, such as a number or a List without objectMessageEnabled, fails the incoming message (rolled back when transacted) and the caller times out.

  • With objectMessageEnabled=true: text, bytes, stream, file, map, value, list, pojo or null

Not known when jmsMessageType is set.

Producer input

text, bytes, stream, file, map or null

Text is sent as a TextMessage; bytes, a stream or a file as a BytesMessage; a Map of simple values as a MapMessage; null as an empty Message. A number, a List or another Serializable object fails unless objectMessageEnabled; a body that is not Serializable is sent as an empty Message.

  • With objectMessageEnabled=true: text, bytes, stream, file, map, value, list, pojo or null

Not known when jmsMessageType or allowNullBody is set.

Producer output

unknown

Unchanged for a message that expects no reply (InOnly). A message that expects one (InOut) gets the body of the reply, as the consumer gives it.

  • With exchangePattern=InOnly: unchanged

  • With disableReplyTo=true: unchanged

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

The component was reworked from Camel 3.8 onwards to be similar to the existing Camel JMS component that is based on Spring JMS.

The reason is to offer many of the same features and functionality from the JMS component, but for users that require lightweight without having to include the Spring Framework.

There are some advanced features in the Spring JMS component that has been omitted, such as shared queues for request/reply. Spring JMS offers fine-grained tunings for concurrency settings, which can be tweaked for dynamic scaling up and down depending on load. This is a special feature in Spring JMS that would require substantial code to implement in SJMS.

The SJMS component does not support for Spring or JTA Transaction, however, support for internal local transactions is supported using JMS or Transaction or Client Acknowledge Mode. See further details below.

Reuse endpoint and send to different destinations computed at runtime

If you need to send messages to a lot of different JMS destinations, it makes sense to reuse a SJMS endpoint and specify the real destination in a message header. This allows Camel to reuse the same endpoint, but send to different destinations. This greatly reduces the number of endpoints created and economizes on memory and thread resources.

Using toD is easier than specifying the dynamic destination with a header

You can specify the destination in the following headers:

Header Type Description

CamelJmsDestinationName

String

The destination name.

For example, the following route shows how you can compute a destination at run time and use it to override the destination appearing in the JMS URL:

  • Java

  • XML

  • YAML

from("file://inbox")
  .to("bean:computeDestination")
  .to("sjms:queue:dummy");
<route>
  <from uri="file:inbox"/>
  <to uri="bean:computeDestination"/>
  <to uri="sjms:queue:dummy"/>
</route>
- route:
    from:
      uri: file:inbox
      steps:
        - to:
            uri: bean:computeDestination
        - to:
            uri: sjms:queue:dummy

The queue name, dummy, is just a placeholder. It must be provided as part of the JMS endpoint URL, but it will be ignored in this example.

In the computeDestination bean, specify the real destination by setting the CamelJmsDestinationName header as follows:

Java-only: setting JMS destination header dynamically
public void setJmsHeader(Exchange exchange) {
   String id = ....
   exchange.getIn().setHeader("CamelJmsDestinationName", "order:" + id");
}

Then Camel will read this header and use it as the destination instead of the one configured on the endpoint. So, in this example Camel sends the message to sjms:queue:order:2, assuming the id value was 2.

Keep in mind that the JMS producer removes both CamelJmsDestinationName headers from the exchange and do not propagate them to the created JMS message to avoid the accidental loops in the routes (in scenarios when the message will be forwarded to another JMS endpoint).

Using toD

If you need to send messages to a lot of different JMS destinations, it makes sense to reuse a SJMS endpoint and specify the dynamic destinations with simple language using toD.

For example, suppose you need to send messages to queues with order types, then using toD could, for example, be done as follows:

Example SJMS route with toD
  • Java

  • XML

  • YAML

from("direct:order")
  .toD("sjms:order-${header.orderType}");
<route>
  <from uri="direct:order"/>
  <toD uri="sjms:order-${header.orderType}"/>
</route>
- route:
    from:
      uri: direct:order
      steps:
        - toD:
            uri: "sjms:order-${header.orderType}"

Local transactions

When using transacted=true then JMS Transacted Acknowledge Mode are in use. The SJMS component supports this from both the consumer and producers. If a consumer is transacted, then the active JMS Session will commit or rollback at the end of processing the message.

SJMS producers that are transacted=true will also defer until the end of processing the message before the active JMS Session will commit or rollback.

You can combine consumer and producer, such as:

Example transacted SJMS route with consumer and producer
  • Java

  • XML

  • YAML

from("sjms:cheese?transacted=true")
  .to("bean:foo")
  .to("sjms:foo?transacted=true")
  .to("bean:bar");
<route>
  <from uri="sjms:cheese?transacted=true"/>
  <to uri="bean:foo"/>
  <to uri="sjms:foo?transacted=true"/>
  <to uri="bean:bar"/>
</route>
- route:
    from:
      uri: sjms:cheese
      parameters:
        transacted: true
      steps:
        - to:
            uri: bean:foo
        - to:
            uri: sjms:foo
            parameters:
              transacted: true
        - to:
            uri: bean:bar

Here the consumer and producer are both transacted, which means that only at the end of processing the message, then both the consumer and the producer will commit (or rollback in case of an exception during routing).

Message Header Format

The SJMS Component uses the same header format strategy used in the Camel JMS Component. This pluggable strategy ensures that messages sent over the wire conform to the JMS Message spec.

For the exchange.in.header the following rules apply for the header keys:

  • Keys starting with JMS or JMSX are reserved.

  • exchange.in.headers keys must be literals and all be valid Java identifiers (do not use dots in the key name).

  • Camel replaces dots & hyphens and the reverse when consuming JMS messages:

    • it is replaced by DOT and the reverse replacement when Camel consumes the message.

    • it is replaced by HYPHEN and the reverse replacement when Camel consumes the message.See also the option jmsKeyFormatStrategy, which allows use of your own custom strategy for formatting keys.

Message Content

The values of the headers sent as JMS properties must either be primitives or their counter-objects (such as Integer, Long, Character). The types, String, CharSequence, Date, BigDecimal and BigInteger are all converted to their toString() representation. All other header values are dropped.

The body is mapped to and from a JMS message as follows (unless the option jmsMessageType forces a type):

Camel body JMS message Body when consumed

String, other text (a CharSequence such as a StringBuilder) or XML Node

TextMessage

String

byte[], InputStream, Reader, ByteBuffer, File, Path or StreamCache

BytesMessage

byte[]

Map (of simple values)

MapMessage

Map

Any body that converts to an InputStream, with jmsMessageType=Stream

StreamMessage

InputStream

null

Message

null

Other Serializable object (such as a number or a List)

ObjectMessage (only with objectMessageEnabled=true, fails otherwise)

the object

Any other object that converts to an InputStream (or File)

BytesMessage

byte[]

Any other object

none: sending fails with a MessageFormatException that names the class of the body

-

With jmsMessageType=Stream the body is converted to an InputStream, and its bytes are written to a StreamMessage. A received StreamMessage is mapped to an InputStream over its bytes, as in the JMS component. With mapJmsMessage=false the body is always the received jakarta.jms.Message.

When pollEnrich or a ConsumerTemplate receives a message from an SJMS endpoint, Camel reads the body and the headers of the message before it commits the session (or acknowledges the message) and closes the JMS consumer, session and connection, as a JMS client may not read the message after that (the ActiveMQ Artemis client streams the body of a large message through the consumer). If the body cannot be read, the receive fails, and the message is rolled back with transacted=true, or recovered with CLIENT_ACKNOWLEDGE, so that it is delivered again. The body is not read at receive time with mapJmsMessage=false (the body is the jakarta.jms.Message itself), and for a StreamMessage (the body is an InputStream that reads the message when it is used).

Clustering

When using InOut with SJMS in a clustered environment, you must either use TemporaryQueue destinations or use a unique reply to destination per InOut producer endpoint. The producer handles message correlation is handled, not with message selectors at the broker.

You should only use queues as reply-to destination types, topics are not recommended or fully supported.

Currently, the only correlation strategy is to use the JMSCorrelationId. The InOut Consumer uses this strategy as well ensuring that all response messages to the included JMSReplyTo destination also have the JMSCorrelationId copied from the request as well.

When the InOut consumer cannot send the reply (for example, as its body cannot be mapped to a JMS message), the incoming message fails as if the route had failed: it is rolled back when transacted=true (or recovered with CLIENT_ACKNOWLEDGE), and the error is logged. No reply is sent, so the caller waits until its requestTimeout.

Batch consuming

The consumer can be configured to receive messages in batches instead of one at a time, by setting batching=true. Instead of one Exchange per message, the route receives a single Exchange whose body is a List<Exchange>, one per JMS message in the batch, with a CamelSjmsBatchSize header giving the batch’s size. Each Exchange in the batch is comparable to the Exchange generated by a non-batching consumer.

Batching only supports the InOnly exchange pattern. There is no reply-to/request-response support for batched consumption — a batch of N unrelated messages has no well-defined single reply, so InOut routes are not supported when batching=true.

A batch completes when either batchSize messages have been received, or the batchInterval — measured from the first message in the batch — has elapsed.

Commit/acknowledgement happens once per batch rather than once per message. With acknowledgementMode=AUTO_ACKNOWLEDGE, messages are acknowledged as they’re received into the batch, before routing — so a failed batch cannot be redelivered. Use transacted=true or acknowledgementMode=CLIENT_ACKNOWLEDGE if the whole batch should be redelivered together on failure.

A failed batch is rolled back and redelivered as a whole, so the route should be idempotent. One bad message fails the whole batch, which is then redelivered: all its messages share the delivery count, and they end up together in the broker’s dead letter queue (if one is configured). How often and how fast the broker redelivers is up to its redelivery policy, for example max-delivery-attempts and redelivery-delay in ActiveMQ Artemis. To avoid this, handle failures per message inside the batch, for example with split(body()) and doTry, or with onException(…​).handled(true). The messages of a redelivered batch have the JMSRedelivered header set.

Similar to the standard consumer, the batch consumer does not preload the JMS properties and payload of each message before adding it to the batch (see eagerLoadingOfProperties). The exchange body and headers are loaded when they are first used. A poison message, one whose payload cannot be read or mapped, throws an exception when it is read. With split(body()), the Splitter reads the SjmsMessage when it copies it. This happens before the split’s doTry, so without additional error handling one bad message fails the whole batch. With transacted=true or CLIENT_ACKNOWLEDGE, the batch is then redelivered. With AUTO_ACKNOWLEDGE, the messages are already acknowledged and the batch is lost.

With eagerLoadingOfProperties=true, the batch consumer loads the JMS properties and payload before the message is added to the batch. For a poison message, where the properties or the payload cannot be loaded, the exception is set on the individual exchange and the body is set to the result of the eagerPoisonBody simple expression (default Poison JMS message payload: ${exception.message}; eagerPoisonBody=false turns this off). The route should check each exchange of the batch for an exception (Exchange.getException()) and handle it. Do this before using split(body()), because the split copies only the message, not the exception.

When the route or the consumer is stopped, Camel’s graceful shutdown first suspends the consumer, so no more messages are received, and waits for the batch being routed before it stops the consumer. A partial batch (fewer than batchSize messages) is handled according to the acknowledgement mode. With transacted=true or CLIENT_ACKNOWLEDGE, the partial batch is not routed, and no new batch starts while the consumer is suspended. Its messages are not acknowledged, so the broker redelivers them after the restart, with the JMSRedelivered header set to true. The redelivery counts towards the broker’s delivery limit. With AUTO_ACKNOWLEDGE, the messages are already acknowledged, so the partial batch is routed as soon as the consumer is suspended, and the graceful shutdown waits for it as well. The graceful shutdown waits up to its timeout (45 seconds by default, see Graceful Shutdown); a batch that is still routed when the timeout is reached is lost (AUTO_ACKNOWLEDGE) or redelivered (transacted=true and CLIENT_ACKNOWLEDGE).

A suspended route (for example by a route policy) handles a partial batch in the same way: with AUTO_ACKNOWLEDGE it is routed right away, and with transacted=true or CLIENT_ACKNOWLEDGE it is routed after the route is resumed.

With concurrentConsumers greater than 1, each consumer collects and routes its own batches, so several batches are processed in parallel.

The batch consumer never sends a reply, so a JMSReplyTo on the incoming messages is ignored.