Camel jms

Camel jms DEFAULT

10.2. Apache Camel JMS-to-JMS Bridge

10.2.1. Configuring the Broker

You need to modify the broker configuration in order to add a VM transport connector.

This is the only modification you should make to the broker configuration file. The Apache Camel JMS-to-JMS bridge must not be embedded inside the broker configuration file. The broker configuration file is not a regular Spring XML file: it is used by a specialized sevice factory, which controls the broker life cycle.

Broker configuration file

In a standalone container, the broker is configured by the following file:

InstallDir/etc/activemq.xml

Adding a VM transport connector

To ensure efficient communication between the Apache Camel JMS-to-JMS bridge and the broker, create a Virtual Machine (VM) transport connector on the broker. Th VM protocol provide a high performace connection between processes that are running inside the same Java Virtual Machine. Example 10.1, “Embedded Apache Camel JMS-to-JMS Bridge” shows how to add a VM connector to the broker configuration in the file.

Example 10.1. Embedded Apache Camel JMS-to-JMS Bridge

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" ... > ... <broker xmlns="http://activemq.apache.org/schema/core" brokerName="${broker-name}" dataDirectory="${data}" start="false"> ... <transportConnectors> <transportConnector name="openwire" uri="tcp://0.0.0.0:0?maximumConnections=1000"/> <!-- Create a VM endpoint to enable embedded connections --><transportConnector uri="vm://local" /> </transportConnectors> </broker> ... </beans>

10.2.2. Configuring ActiveMQ JMS Connections

The Camel ActiveMQ component

The Camel ActiveMQ component (hosted in the Apache ActiveMQ project) is a Camel component that is used to integrate the Apache ActiveMQ Java client with Camel. Using the Camel ActiveMQ component, it is possible to define JMS consumer endpoints (at the start of a Camel route) and JMS producer endpoints (at the end of a Camel route).

Apache Camel bridge configuration file

The simplest way to configure the Apache Camel JMS-to-JMS file is to create a Spring XML file and copy it into the hot deploy directory. For the current example, we assume that the bridge configuration is stored in the following file:

InstallDir/deploy/jms-bridge.xml

Subsequently, if you need to undeploy the Spring XML file, you can do so by deleting the file from the directory while the Karaf container is running.

The following code example shows how to define and configure a Camel ActiveMQ endpoint by adding Spring XML code to the bridge configuration file, .

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" ... > ... <!-- -- Configure the ActiveMQ broker connection --> <bean id="amqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="vm://local?create=false"/> </bean> <bean id="jmsConfig" class="org.apache.camel.component.jms.JmsConfiguration"> <property name="connectionFactory" ref="amqConnectionFactory"/> <property name="concurrentConsumers" value="10"/> </bean> <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent"> <property name="configuration" ref="jmsConfig"/> </bean> ... </beans>

Note the following points about this example:

  • The bean with ID, , and of type, , defines the Camel ActiveMQ component instance. This bean overrides the default ActiveMQ component instance and implicitly associates the bean ID value, , with the URI scheme of the same name. The URI scheme can then be used to define endpoints of this component in a Camel route.

  • The bean with ID, , is used to configure the ActiveMQ component (and supports many additional options).

  • The bean with ID, , is a JMS connection factory that is used to create connections to the ActiveMQ broker. Note the following attribute settings:

    • The attribute specifies the transport protocol for connecting to the broker. In this case, the protocol is , which uses the Java Virtual Machine to route messages directly to and from the embedded broker.

Defining an endpoint with the activemq scheme

The bean ID of the ActiveMQ component (in this example, ) is implicitly adopted as the URI scheme for defining ActiveMQ endpoints in Camel routes. For example, to define an endpoint that connects to the QueueA queue in the ActiveMQ broker, use the following URI:

activemq:queue:QueueA

To define an endpoint that connects to the topic in the ActiveMQ broker, use the following URI:

activemq:topic:TopicA

Other types of ActiveMQ connection factory

ActiveMQ provides a variety of different types of JMS connection factory, as follows:

For ordinary JMS connections (includes support for JMS authentication).

For configuring JMS connections over SSL/TLS (encrypted transport).

For integrating the ActiveMQ client with an XA transaction manager.

For more details about the Camel ActiveMQ component, see the following references:

  • The ActiveMQ component chapter from the EIP Component Reference.

  • The community documentation for the ActiveMQ Component.

10.2.3. Configuring Third-Party JMS Connections

The Camel JMS component is a general purpose JMS integration point that can be used to integrate Apache Camel with any JMS client library. Using the Camel JMS component, it is possible to define JMS consumer endpoints (at the start of a Camel route) and JMS producer endpoints (at the end of a Camel route).

You can connect to a third-party JMS broker using either of the following approaches:

Reference a connection factory bean

You can configure connections to a third-party JMS provider by instantiating a instance directly as a Spring bean. You can then inject this third-party connection factory bean into the configuration of the Camel JMS component.

For example, you can instantiate and reference a WebSphere MQ queue connection factory by adding the following XML code to the bridge configuration, :

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" ... > ... <!-- Configure IBM WebSphere MQ connection factory --> <bean id="websphereConnectionFactory" class="com.ibm.mq.jms.MQConnectionFactory"> <property name="transportType" value="1"/> <property name="hostName" value="localhost"/> <property name="port" value="1414"/> <property name="queueManager" value="QM_TEST"/> </bean> <bean id="websphereConfig" class="org.apache.camel.component.jms.JmsConfiguration"> <property name="connectionFactory" ref="websphereConnectionFactory"/> <property name="concurrentConsumers" value="10"/> </bean> <bean id="websphere" class="org.apache.camel.component.jms.JmsComponent"> <property name="configuration" ref="websphereConfig"/> </bean> ... </beans>

Look up a connection factory in JNDI

You can use JNDI to configure connections to a third-party JMS provider by configuring the attribute of Camel's class to reference a Spring instance.

For example, to look up a WebSphere MQ connection factory in an LDAP based JNDI server, you could add the following XML code to the bridge configuration file, , as follows:

<beans ... > ... <!-- Configure a Spring JNDI template instance --> <bean id="jmsJndiTemplate" class="org.springframework.jndi.JndiTemplate"> <property name="environment"> <props> <prop key="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</prop><prop key="java.naming.provider.url">ldap://server.company.com/o=company_us,c=us</prop> </props> </property> </bean> <bean id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiTemplate" ref="jmsJndiTemplate"/> <property name="jndiName" value="jms/websphere-test"/> </bean> <bean id="jndiDestinationResolver" class="org.springframework.jms.support.destination.JndiDestinationResolver"> <property name="jndiTemplate" ref="jmsJndiTemplate"/> </bean> <bean id="websphereConfig" class="org.apache.camel.component.jms.JmsConfiguration"> <property name="connectionFactory" ref="jmsConnectionFactory"/> <property name="destinationResolver" ref="jndiDestinationResolver"/> <property name="concurrentConsumers" value="10"/> </bean> <bean id="websphere" class="org.apache.camel.component.jms.JmsComponent"> <property name="configuration" ref="websphereConfig"/> </bean> ... </beans>

For more details about the Camel JMS component, see the following references:

  • The JMS component chapter from the EIP Component Reference.

  • The community documentation for the JMS Component.

10.2.4. Defining Apache Camel Routes

Apache Camel is a sophisticated and flexible routing engine. At the simplest level, you can use it move JMS messages back and forth between an ActiveMQ broker and a third-party JMS provider. But Camel can do much more. You can insert processors into a route to process the message contents and Camel also has built in processors that implement a wide variety of Enterprise Integration Patterns.

The description in this section—which shows you how to define simple pass-through routes—only scratches the surface of Camel's capabilities. It is recommended that you take a look at some of the references at the end of this section to get a better idea of Camel's capabilities.

To create a JMS endpoint in an Apache Camel route, specify an endpoint URI according to the following queue syntax:

JmsUriScheme:queue:QueueName[?Options]

Or according to the following topic syntax:

JmsUriScheme:topic:TopicName[?Options]

Where the URI scheme, JmsUriScheme, is equal to the bean ID of the corresponding JMS component (or ActiveMQ component) defined in Spring XML—for example, or .

In the XML language, Camel routes are defined inside a element. Each route definition appears inside a element, starting with a element (which defines a consumer endpoint for receiving messages) and ending with a element (which defines a producer endpoint for sending messages).

For example, to perform simple, straight-through routing, consuming messages from the queue on the ActiveMQ broker and passing them straight on to the queue on the WebSphere messaging system, you can use the following route definition:

<camelContext xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="activemq:queue:TEST.FOO"/> <to uri="websphere:queue:TEST.FOO"/> </route> </camelContext>

The following sample Camel routes give examples of how to route queues and topics into and out of the ActiveMQ broker. To define these routes, you would add them to the bridge configuration file, .

<beans ... > ... <camelContext xmlns="http://camel.apache.org/schema/spring"> <!-- Route outgoing QueueA queue --> <route> <from uri="activemq:queue:QueueA?mapJmsMessage=false"/> <to uri="websphere:queue:QueueA"/> </route> <!-- Route outgoing TopicA topic --> <route> <from uri="activemq:topic:TopicA?mapJmsMessage=false"/> <to uri="websphere:topic:TopicA"/> </route> <!-- Route incoming QueueX queue --> <route> <from uri="websphere:queue:QueueX?mapJmsMessage=false"/> <to uri="activemq:queue:QueueX"/> </route> <!-- Route incoming TopicX topic --> <route> <from uri="websphere:topic:TopicX?mapJmsMessage=false"/> <to uri="activemq:topic:TopicX"/> </route> </camelContext> </beans>

In the preceding example, the consumer endpoints are configured with the set to . This prevents the JMS message from being parsed into the standard Java data format, thus ensuring that the message is passed straight through without processing, which gives optimum performance for a pass-through route.

On the other hand, if you want to perform any processing on the message content or the message headers, you should remove this option (or set it to ).

If you want to take advantage of the content completion feature of your XML editor, you can configure your editor to fetch the Camel schema from the following location:

http://camel.apache.org/schema/spring/camel-spring.xsd

The preceding location always holds the latest version of the Camel schema. If you want to specify a particular version of the schema, you can use the version-specific location:

http://camel.apache.org/schema/spring/camel-spring-Version.xsd

Apache Camel is a sophisticated routing and integration tool. To get a better idea of the capabilities of this tool, please consult the following guides from the JBoss Fuse library:

  • Implementing Enterprise Integration Patterns

  • Routing Expression and Predicate Languages

  • EIP Component Reference

Sours: https://access.redhat.com/documentation/en-us/red_hat_amq/6.2/html/using_networks_of_brokers/fmqnetworksjmstojms-camel

Apache Camel + JMS (ActiveMQ) Hello World Example

Overview

Previous tutorial we had implemented Apache Camel Example to use File Component and seen what are Routes and Components.In this tutorial we will making use of Apache Camel JMS Component. We will be reading from one JMS Queue and sending the message to another jms queue. Also we will be making use of ActiveMQ queues.

Technology Stack

We will be making use of-
  • Java 1.8
  • Apache Camel 3.0.0-M2
  • Maven
  • ActiveMQ 5.15.9

Implementation

ActiveMQ Installation and Startup

Apache Camel JMS implementation

The maven project we will be creating is as follows-
Apache Camel Maven Project
The pom.xml will be as follows- For this example we make use of Java DSL for writing Routes. A Routeconsists of Message Channel for using which applications communicate using Messages. The end points of these message channels either consume of produce messages.

Apache Camel Endpoints

What are Components?

Componentact as an endpoint factory using which we can interact with external systems. Camel provides a large number of components using which we can interact with externals systems.
We have to transfer a data from one JMS Queue to another JMS Queue so we make use of the JMS Component.
Apache Camel Components
In Apache Camel for creating a route we need to extend RouteBuilder class and override configure method. Then in configure method we define our route. So our route using Java DSL will be as follows-

What is CamelContext?

We cannot run our Camel Application only using the route. We also need the camel context which acts as a runtime system that runs and manages the routes. It is responsible for all managing all aspects of a route.
Apache Camel Maven Project
We create and configure Apache Camel Component using the following steps -
  • 1. Create CamelContext.
  • 2. Add routes to the CamelContext.
  • 3. Start the CamelContext. So that the Routes get executed.
  • 4. Stop the Camel Context.
We define the CamelContext in the CamelMain class as follows- Run the Application. We will see that one queue created now.
Apache Camel Route1
If we send a message in codeusingjava-inputqueue it gets transferred to the codeusingjava-outputqueue .
Apache Camel Route2

Apache Camel Route3

Downloads-

Apache Camel JMS Example
Sours: https://www.codeusingjava.com
  1. Camaro price philippines
  2. Lithium and xanax
  3. Wrapify reviews reddit

Using ActiveMQ with Apache Camel - with example

How to send and receive messages from an ActiveMQ Artemis message broker using Camel’s JMS component and Spring Boot

Using ActiveMQ with Apache Camel - with example

Tags: Apache ActiveMQ, Apache Camel • Comments

Want to use JMS? Apache Camel makes it pretty easy to send and receive messages from any message broker which supports the JMS API.

In this article, I’ll talk about configuring Apache Camel to work with one of the most common message brokers, Apache ActiveMQ. As usual, there’s some example code along the way for you to copy and try out.

What you need

To send and receive messages with Apache Camel and ActiveMQ, you’ll need:

  • An ActiveMQ broker to connect to, to send and receive messages. You can download ActiveMQ from its web site and follow the documentation to run it. Alternatively, you can embed a broker inside your Java application, or run ActiveMQ in a Docker container.

  • An ActiveMQ connection factory configured in your application, which is set up with the right parameters to connect to your ActiveMQ broker. The way to do this varies a lot between different Java platforms and application servers (Spring Boot, OSGi, Wildfly, etc.). But, the main principle is to declare an instance of ActiveMQ’s connection factory object, and give it some properties to connect to your broker, like host, port, etc.

    Spring Boot is a bit of a special case. It will create a ConnectionFactory for you automatically, if certain properties are set. See further below for more info about this.

  • Configure an instance of Camel’s JMS component. This is so that when you use the endpoint in your routes, Camel will know which Connection Factory it should use. The usual way of configuring a component in Camel is:

    1. create an instance of the Component object (e.g. )

    2. set the component’s properties (e.g. )

    3. add the component to Camel’s bean registry.

    If you’re using Spring or Spring Boot, then Camel uses your Spring context as a registry. Just define your Camel component as a Spring Bean (e.g. using , or Spring XML definitions) and Camel will be able to see and use it.

Of course, Apache Camel should also be up and running in your project. I won’t cover Camel set-up in this article, but if you want to read about how to start a new Camel project, then take a look at my other articles:

In this article I’m going to use Apache ActiveMQ Artemis which is the latest generation of ActiveMQ.

Which ActiveMQ to use?

There are two different projects under the ActiveMQ name – ActiveMQ “Classic” and ActiveMQ Artemis. Each of them is a different project entirely! But they share the same ActiveMQ name. Yes, it’s confusing.

I recommend using ActiveMQ Artemis, as it’s a very active project, and is where new features are being added, such as AMQP support, and support for JMS 2.0. So I’m going to use Artemis.

But much of this tutorial can also be applied to ActiveMQ Classic (5.x) if you’re still using that.

Creating the Connection Factory and Camel JMS component

First we need to make sure we have a . Camel needs a ConnectionFactory to be able to create connections to your message broker.

A ConnectionFactory is a Java interface for defining objects that will store connection details to message brokers - things like host, port, usernames and passwords.

ActiveMQ Artemis has its own implementation of . Simply define an instance of this Artemis connection factory, create an instance of Camel’s , and wire them up together.

For example, in Spring Java configuration:

Since I’m defining a Camel JMS component as a Spring bean, Camel will see it, and use it whenever I refer to the JMS component in my routes.

Want to learn Apache Camel?

Sample the first chapters of my Apache Camel book for beginners, for free. You'll learn the basics of Camel, all the core concepts, and see, step-by-step, how to create your first Camel project.

Get this 38-page book for free

Get the book sample for free, 📙
plus email lessons to get you started
with Apache Camel

📩 By sharing your email address, you're joining my free Intro to Camel email course, and newsletter. I'll email you the sample Free Edition of my full book, Camel Step-by-Step, along with Camel beginner tips, and my latest tutorials and products. I don't share your email address with anyone else, and you can unsubscribe at any time. (No worries!) Questions?

Spring Boot magic explained: connection factories & Camel components

Using Spring Boot? It works a little differently. Due to its convention-over-configuration approach, it will do a bunch of stuff for you.

If you’re wondering why everything seems to work magically out-of-the-box, then here’s why:

🐇 MAGIC TRICK 1 🐇: If you’re using Spring Boot, it can create a ConnectionFactory for you automatically.

Spring Boot will create an ActiveMQ Artemis connection factory, if:

  • it finds the Artemis client libraries on your classpath,

  • and you specify the broker details in properties beginning with ,

  • and you haven’t already defined a connection factory yourself.

This is explained (briefly) in the Spring Boot docs:

Extract from the Spring Boot documentation showing which properties can be used to configure Artemis connection factory

🎩 MAGIC TRICK 2 🎩: If you’re using one of Camel’s dependencies, it can create and configure components for you automatically.

If you add to your application’s Maven dependencies, then Camel will configure the JMS component automatically – if it can find a ConnectionFactory.

So, in practice, this means that to configure JMS messaging with ActiveMQ Artemis for Camel on Spring Boot, you just need to do 2 things:

  • Add the and ActiveMQ client dependencies to Maven.

  • Set the properties in your file.

Using the JMS component in a route

Once you have configured your JMS component and wired it to your connection factory, you can send and receive messages from ActiveMQ by using the endpoint in your routes.

For example, to receive a message from ActiveMQ:

Or, to send a message to ActiveMQ:

With that in mind, let’s look at the example!

Example - connecting to ActiveMQ from Camel using Spring Boot

So now let’s put it all together. Here’s an example of how to add ActiveMQ Artemis JMS messaging capabilities to an Apache Camel project, on Spring Boot:

  1. First, make sure your project imports the Spring Boot and Camel BOMs (Bill-of-Materials). This is done in your Maven POM, and will help us set our version numbers correctly:

  2. Add the Artemis client library, and the Camel JMS component (for Spring Boot) to your Maven POM, like this:

    • The contains the libraries needed to connect to ActiveMQ. When Spring Boot detects this on the classpath, it will create a connection factory to ActiveMQ Artemis.

    • The contains Camel’s JMS component. As it is in the springboot package, and it is named -starter, we know it will also do some autoconfiguration for us. In this case, it will automatically configure Camel’s JMS component to use our Artemis connection factory.

    Notice how I’m not specifying the version number of these dependencies; because the Spring Boot and Camel BOMs will set them for us.

  3. Set the Artemis connection properties in your file. You must use exactly these property names:

    If you’re not using Spring Boot, you will need to do some of this configuration manually. You should create a Connection Factory and then manually wire this to Camel’s JMS component. See a Java example or an XML example.

  4. Define a Camel route which consumes from a queue. Start the route with a From step, using the URL .

    In this example, I’m receiving a message from the queue and writing it to a log:

  5. Define another route to write a message to a queue. Here I’m using a Timer component to trigger sending a message to a queue, every 5 seconds:

  6. Now make sure your broker is started, and then run your Camel Spring Boot application:

    And you should see this output in the console log:

    2020-02-01 12:01:17.102 INFO 21743 — [er[HELLO.WORLD]] route2 : Received a message - HELLO from Camel!

Congrats! You’ve now written a Camel application which reads and writes messages to a queue in ActiveMQ!

Just want to see the complete, worked example? Click on the button below to see the completed application:

Get the example code on GitHub

Summary

To send and receive messages to ActiveMQ using Apache Camel, make sure you configure a connection factory, create and configure Camel’s JMS component, and then use the endpoint URI in your Camel routes.

If you’re using Spring Boot, you can skip the connection factory and Camel component configuration by using the right properties ( or ) and using Camel’s Maven dependency.

Questions? Comments? Do I need to update anything in this article? Let me know your thoughts in the comments section below!

Don't miss my next post!

Join my newsletter to enjoy my latest tutorials, thoughts and recommended links, no more than 2-3 times per month. Put your details in the form below to join today.

Photo by Shiro Yamamoto on Unsplash↗  

Sours: https://tomd.xyz/camel-activemq/

JMS Component

Using ActiveMQ
If you are using Apache ActiveMQ, you should prefer the ActiveMQ component as it has been optimized for ActiveMQ. All of the options and samples on this page are also valid for the ActiveMQ component.
Transacted and caching
See section Transactions and Cache Levels below if you are using transactions with JMS as it can impact performance.

The JMS component allows messages to be sent to (or consumed from) a JMS Queue or Topic. The implementation of the JMS Component uses Spring's JMS support for declarative transactions, using Spring's for sending and a for consuming.

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

<dependency><groupId>org.apache.camel</groupId><artifactId>camel-jms</artifactId><version>x.x.x</version></dependency>

URI format

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

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

You can include the optional prefix, if you prefer:

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

You append query options to the URI using the following format,

Notes

Using ActiveMQ

The JMS component reuses Spring 2's for sending messages. This is not ideal for use in a non-J2EE container and typically requires some caching in the JMS provider to avoid poor performance.

If you intend to use Apache ActiveMQ as your Message Broker - which is a good choice as ActiveMQ rocks , then we recommend that you either:

  • Use the ActiveMQ component, which is already optimized to use ActiveMQ efficiently
  • Use the in ActiveMQ.

Transactions and Cache Levels


If you are consuming messages and using transactions () then the default settings for cache level can impact performance.
If you are using XA transactions then you cannot cache as it can cause the XA transaction to not work properly.

If you are not using XA, then you should consider caching as it speeds up performance, such as setting .

Through Camel 2.7.x, the default setting for is . You will need to explicitly set .
In Camel 2.8 onwards, the default setting for is . This default auto detects the mode and sets the cache level accordingly to:

  • CACHE_CONSUMER = if transacted=false
  • CACHE_NONE = if transacted=true

So you can say the default setting is conservative. Consider using if you are using non-XA transactions.

Durable Subscriptions

If you wish to use durable topic subscriptions, you need to specify both clientId and durableSubscriptionName. The value of the must be unique and can only be used by a single JMS connection instance in your entire network. You may prefer to use Virtual Topics instead to avoid this limitation. More background on durable messaging here.

Message Header Mapping

When using message headers, the JMS specification states that header names must be valid Java identifiers. So, by default, Camel ignores any headers that do not match this rule. So try to name your headers as if they are valid Java identifiers. One benefit of doing this is that you can then use your headers inside a JMS Selector (whose SQL92 syntax mandates Java identifier syntax for headers).

A simple strategy for mapping header names is used by default. The strategy is to replace any dots and hyphens in the header name as shown below and to reverse the replacement when the header name is restored from a JMS message sent over the wire. What does this mean? No more losing method names to invoke on a bean component, no more losing the filename header for the File Component, and so on.

The current header name strategy for accepting header names in Camel is as follows:

  • Dots are replaced by and the replacement is reversed when Camel consume the message
  • Hyphen is replaced by and the replacement is reversed when Camel consumes the message
  • Test if the name is a valid java identifier using the JDK core classes.
  • If the test is successful, the header is added and sent over the wire; otherwise it is dropped (and logged at level).

Options

You can configure many different properties on the JMS endpoint which map to properties on the JMSConfiguration POJO.

Mapping to Spring JMS
Many of these properties map to properties on Spring JMS, which Camel uses for sending and receiving messages. So you can get more information about these properties by consulting the relevant Spring documentation.

The options are divided into two tables, the first one with the most common options used. The latter contains the rest.

Most commonly used options

Option Default Value Description
Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions. You may prefer to use Virtual Topics instead.
Specifies the default number of concurrent consumers.
If , a producer will behave like a InOnly exchange with the exception that header is sent out and not be suppressed like in the case of . Like the producer will not wait for a reply. A consumer with this flag will behave like . This feature can be used to bridge requests to another queue so that a route on the other queue will send it´s response directly back to the original .
The durable subscriber name for specifying durable topic subscriptions. The option must be configured as well.
Specifies the maximum number of concurrent consumers.
Set to , if you want to send message using the QoS settings specified on the message, instead of the QoS settings on the JMS endpoint. The following three headers are considered , , and . You can provide all or only some of them. If not provided, Camel will fall back to use the values from the endpoint instead. So, when using this option, the headers override the values from the endpoint. The option, by contrast, will only use options set on the endpoint, and not values from the message header.
Provides an explicit ReplyTo destination, which overrides any incoming value of . If you do Request Reply over JMS then read the section further below for more details.
Camel 2.9: Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: , , or . By default Camel will use temporary queues. However if has been configured, then is used by default. This option allows you to use exclusive queues instead of shared ones. See further below for more details, and especially the notes about the implications if running in a clustered environment.
Producer only: The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. See below in section About time to live for more details.
Sets the JMS Selector, which is an SQL 92 predicate that is used to filter messages within the broker. You may have to encode special characters such as = as %3D Before Camel 2.3.0, we don't support this option in CamelConsumerTemplate
When sending messages, specifies the time-to-live of the message (in milliseconds). See below in section About time to live for more details.
Specifies whether to use transacted mode for sending/receiving messages using the InOnly Exchange Pattern.
Camel 2.1: Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. From Camel 2.8 onwards also the JMS producers is tested as well.

All the other options

Option Default Value Description
Specifies whether the consumer accept messages while it is stopping.
The JMS acknowledgement name, which is one of: , , ,
The JMS acknowledgement mode defined as an Integer. Allows you to set vendor-specific extensions to the acknowledgment mode. For the regular modes, it is preferable to use the instead.
If , Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations, such as when a is set (incidentally, Camel will set the option to , if a is set)
Camel 2.9: Whether the processes the Exchangeasynchronously. If enabled then the may pickup the next message from the JMS queue, while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100% strictly in order. If disabled (as default) then the Exchange is fully processed before the will pickup the next message from the JMS queue. Note if has been enabled, then does not run asynchronously, as transactions must be executed synchronously (Camel 3.0 may support async transactions).
Specifies whether the consumer container should auto-startup.
Sets the cache level by name for the underlying JMS resources. Possible values are: , , , , and . The default setting for Camel 2.8 and newer is . For Camel 2.7.1 and older the default is . See the Spring documentation and Transactions Cache Levels for more information.
Sets the cache level by ID for the underlying JMS resources. See option for more details.
The consumer type to use, which can be one of: or . The consumer type determines which Spring JMS listener to use. will use , will use . This option was temporary removed in Camel 2.7 and 2.8. But has been added back from Camel 2.9 onwards.
The default JMS connection factory to use for the and , if neither is specified.
Specifies whether persistent delivery is used by default.
Specifies the JMS Destination object to use on this endpoint.
Specifies the JMS destination name to use on this endpoint.
A pluggable that allows you to use your own resolver (for example, to lookup the real destination in a JNDI registry).
Camel 2.8: Use this option to force disabling time to live. For example when you do request/reply over JMS, then Camel will by default use the value as time to live on the message being sent. The problem is that the sender and receiver systems have to have their clocks synchronized, so they are in sync. This is not always so easy to archive. So you can use to not set a time to live value on the sent message. Then the message will not expire on the receiver system. See below in section About time to live for more details.
Enables eager loading of JMS properties as soon as a message is received, which is generally inefficient, because the JMS properties might not be required. But this feature can sometimes catch early any issues with the underlying JMS provider and the use of JMS properties. This feature can also be used for testing purposes, to ensure JMS properties can be understood and handled correctly.
Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions.
Camel 2.8.2, 2.9: Specifies a to be invoked in case of any uncaught exceptions thrown while processing a . By default these exceptions will be logged at the WARN level, if no has been configured. From Camel 2.9.1: onwards you can configure logging level and whether stack traces should be logged using the below two options. This makes it much easier to configure, than having to code a custom .
Camel 2.9.1: Allows to configure the default logging level for logging uncaught exceptions.
Camel 2.9.1: Allows to control whether stacktraces should be logged or not, by the default .
Set if the , or qualities of service should be used when sending messages. This option is based on Spring's . The , and options are applied to the current endpoint. This contrasts with the option, which operates at message granularity, reading QoS properties exclusively from the Camel In message headers.
Specifies whether the listener session should be exposed when consuming messages.
Camel 2.7: When using Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to to force Camel to send the original JMS message that was received.
Specifies the limit for idle executions of a receive task, not having received any message within its execution. If this limit is reached, the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the setting).
Camel 2.8.2, 2.9: Specify the limit for the number of consumers that are allowed to be idle at any given time.
Allows you to force the use of a specific implementation for sending JMS messages. Possible values are: , , , , . By default, Camel would determine which JMS message type to use from the In body type. This option allows you to specify it.
Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: and . The strategy will safely marshal dots and hyphens ( and ). The strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the and refer to it using the notation.
Allows you to use your own implementation of the interface. Camel uses as default. Can be used for testing purpose, but not used much as stated in the spring API docs.
If , Camel will create a , if there is no injected when option .
The JMS connection factory used for consuming messages.
Specifies whether Camel should auto map the received JMS message to an appropiate payload type, such as to a etc. See section about how mapping works below for more details.
The number of messages per task. -1 is unlimited.
Limits the number of messages fetched at most, when browsing endpoints using Browse or JMX API.
To use a custom Spring so you can be 100% in control how to map to/from a .
When sending, specifies whether message IDs should be added.
Specifies whether timestamps should be enabled by default on sending messages.
The password for the connector factory.
Values greater than 1 specify the message priority when sending (where 0 is the lowest priority and 9 is the highest). The option must also be enabled in order for this option to have any effect.
Specifies whether to inhibit the delivery of messages published by its own connection.
None The timeout for receiving messages (in milliseconds).
Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds. The default is 5000 ms, that is, 5 seconds.
Camel 2.9.1: Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: for exclusive or shared w/ . And for shared without . Some JMS brokers such as IBM WebSphere may require to set the to work.
Sets the JMS Selector using the fixed name to be used so you can filter out your own replies from the others when using a shared queue (that is, if you are not using a temporary reply queue).
Specifies whether to use persistent delivery by default for replies.
@deprecated: Enabled by default, if you specify a and a .
Allows you to specify a custom task executor for consuming messages.
Camel 2.6: To use when using Spring 2.x with Camel. Allows you to specify a custom task executor for consuming messages.
The JMS connection factory used for sending messages.
@deprecated: Specifies whether to use transacted mode for sending messages using the InOut Exchange Pattern. Applies only to producer endpoints. See section Enabling Transacted Consumption for more details.
The Spring transaction manager to use.
The name of the transaction to use.
The timeout value of the transaction, if using transacted mode.
If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side, then the caused will be send back in response as a . If the client is Camel, the returned is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example, using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled, this option takes precedence. The caught exception is required to be serializable. The original on the consumer side can be wrapped in an outer exception such as when returned to the producer.
You can transfer the exchange over the wire instead of just the body and headers. The following fields are transferred: In body, Out body, Fault body, In headers, Out headers, Fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at level.
The username for the connector factory.
Specifies whether should always be used as for InOut messages.
@deprecated (removed from Camel 2.5 onwards): Specifies whether the old JMS API should be used.

Message Mapping between JMS and Camel

Camel automatically maps messages between and .

When sending a JMS message, Camel converts the message body to the following JMS message types:

Body Type JMS Message Comment
 
The DOM will be converted to .
 
 
 
 
 
 
 

When receiving a JMS message, Camel converts the JMS message to the following body type:

JMS Message Body Type

Disabling auto-mapping of JMS messages

You can use the option to disable the auto-mapping above. If disabled, Camel will not try to map the received JMS message, but instead uses it directly as the payload. This allows you to avoid the overhead of mapping and let Camel just pass through the JMS message. For instance, it even allows you to route JMS messages with classes you do not have on the classpath.

Using a custom MessageConverter

You can use the option to do the mapping yourself in a Spring class.

For example, in the route below we use a custom message converter when sending a message to the JMS order queue:

from("file:).to("jms:queue:order?messageConverter=#myMessageConverter");

You can also use a custom message converter when consuming from a JMS destination.

Controlling the mapping strategy selected

You can use the jmsMessageType option on the endpoint URL to force a specific message type for all messages.
In the route below, we poll files from a folder and send them as as we have forced the JMS producer endpoint to use text messages:

from("file:).to("jms:queue:order?jmsMessageType=Text");

You can also specify the message type to use for each messabe by setting the header with the key . For example:

from("file:).setHeader("CamelJmsMessageType", JmsMessageType.Text).to("jms:queue:order");

The possible values are defined in the class, .

Message format when sending

The exchange that is sent over the JMS wire must conform to the JMS Message spec.

For the the following rules apply for the header keys:

  • Keys starting with or are reserved.
  • 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 when consuming JMS messages:
    is replaced by and the reverse replacement when Camel consumes the message.
    is replaced by and the reverse replacement when Camel consumes the message.
  • See also the option , which allows use of your own custom strategy for formatting keys.

For the , the following rules apply for the header values:

  • The values must be primitives or their counter objects (such as , , ). The types, , , , and are all converted to their representation. All other types are dropped.

Camel will log with category at DEBUG level if it drops a given header value. For example:

2008-07-09 06:43:04,046 [main ] DEBUG JmsBinding - Ignoring non primitive header: order of class: org.apache.camel.component.jms.issues.DummyOrder with value: DummyOrder{orderId=333, itemId=4444, quantity=2}

Message format when receiving

Camel adds the following properties to the when it receives a message:

Property Type Description
The reply destination.

Camel adds the following JMS properties to the In message headers when it receives a JMS message:

Header Type Description
The JMS correlation ID.
The JMS delivery mode.
The JMS destination.
The JMS expiration.
The JMS unique message ID.
The JMS priority (with 0 as the lowest priority and 9 as the highest).
Is the JMS message redelivered.
The JMS reply-to destination.
The JMS timestamp.
The JMS type.
The JMS group ID.

As all the above information is standard JMS you can check the JMS documentation for further details.

About using Camel to send and receive messages and JMSReplyTo

The JMS component is complex and you have to pay close attention to how it works in some cases. So this is a short summary of some of the areas/pitfalls to look for.

When Camel sends a message using its , it checks the following conditions:

  • The message exchange pattern,
  • Whether a was set in the endpoint or in the message headers,
  • Whether any of the following options have been set on the JMS endpoint: , , .

All this can be a tad complex to understand and configure to support your use case.

JmsProducer

The behaves as follows, depending on configuration:

Exchange Pattern Other options Description
InOut - Camel will expect a reply, set a temporary , and after sending the message, it will start to listen for the reply message on the temporary queue.
InOut is set Camel will expect a reply and, after sending the message, it will start to listen for the reply message on the specified queue.
InOnly - Camel will send the message and not expect a reply.
InOnly is set By default, Camel discards the destination and clears the header before sending the message. Camel then sends the message and does not expect a reply. Camel logs this in the log at level (changed to level from Camel 2.6 onwards. You can use to instruct Camel to keep the . In all situations the does not expect any reply and thus continue after sending the message.

JmsConsumer

The behaves as follows, depending on configuration:

Exchange Pattern Other options Description
InOut - Camel will send the reply back to the queue.
InOnly - Camel will not send a reply back, as the pattern is InOnly.
- This option suppresses replies.

So pay attention to the message exchange pattern set on your exchanges.

If you send a message to a JMS destination in the middle of your route you can specify the exchange pattern to use, see more at Request Reply.
This is useful if you want to send an message to a JMS topic:

from("activemq:queue:in") .to("bean:validateOrder") .to(ExchangePattern.InOnly, "activemq:topic:order") .to("bean:handleOrder");

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 JMS 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.

You can specify the destination in the following headers:

Header Type Description
A destination object.
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:

from("file:) .to("bean:computeDestination") .to("activemq:queue:dummy");

The queue name, , 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 bean, specify the real destination by setting the header as follows:

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 , assuming the value was 2.

If both the and the headers are set, takes priority.

Configuring different JMS providers

You can configure your JMS provider in Spring XML as follows:

<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring"><jmxAgent id="agent" disabled="true"/></camelContext><bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent"><property name="connectionFactory"><bean class="org.apache.activemq.ActiveMQConnectionFactory"><property name="brokerURL" value="vm://localhost?broker.persistent=false&amp;broker.useJmx=false"/></bean></property></bean>

Basically, you can configure as many JMS component instances as you wish and give them a unique name using the attribute. The preceding example configures an component. You could do the same to configure MQSeries, TibCo, BEA, Sonic and so on.

Once you have a named JMS component, you can then refer to endpoints within that component using URIs. For example for the component name, , you can then refer to destinations using the URI format, . You can use the same approach for all other JMS providers.

This works by the SpringCamelContext lazily fetching components from the spring context for the scheme name you use for EndpointURIs and having the Component resolve the endpoint URIs.

Using JNDI to find the ConnectionFactory

If you are using a J2EE container, you might need to look up JNDI to find the JMS rather than use the usual mechanism in Spring. You can do this using Spring's factory bean or the new Spring XML namespace. For example:

<bean id="weblogic" class="org.apache.camel.component.jms.JmsComponent"><property name="connectionFactory" ref="myConnectionFactory"/></bean><jee:jndi-lookup id="myConnectionFactory" jndi-name="jms/connectionFactory"/>

See The jee schema in the Spring reference documentation for more details about JNDI lookup.

Concurrent Consuming

A common requirement with JMS is to consume messages concurrently in multiple threads in order to make an application more responsive. You can set the option to specify the number of threads servicing the JMS endpoint, as follows:

from("jms:SomeQueue?concurrentConsumers=20"). bean(MyClass.class);

You can configure this option in one of the following ways:

  • On the ,
  • On the endpoint URI or,
  • By invoking directly on the .

Request-reply over JMS

Camel supports Request Reply over JMS. In essence the MEP of the Exchange should be when you send a message to a JMS queue.
The detects the and provides a header with the reply destination to be used. By default Camel uses a temporary queue, but you can use the option on the endpoint to specify a fixed reply queue (see more below about fixed reply queue).

Camel will automatic setup a consumer which listen on the reply queue, so you should not do anything.
This consumer is a Spring which listen for replies. However it's fixed to 1 concurrent consumer.
That means replies will be processed in sequence as there are only 1 thread to process the replies. If you want to process replies faster, then we need to use concurrency. But not using the option. We should use the from the Camel DSL instead, as shown in the route below:

from(xxx) .inOut().to("activemq:queue:foo") .threads(5) .to(yyy) .to(zzz);

In this route we instruct Camel to route replies asynchronously using a thread pool with 5 threads.

Request-reply over JMS and using a shared fixed reply queue

If you use a fixed reply queue when doing Request Reply over JMS as shown in the example below, then pay attention.

from(xxx) .inOut().to("activemq:queue:foo?replyTo=bar") .to(yyy)

In this example the fixed reply queue named "bar" is used. By default Camel assumes the queue is shared when using fixed reply queues, and therefore it uses a to only pickup the expected reply messages (eg based on the ). See next section for exclusive fixed reply queues. That means its not as fast as temporary queues. You can speedup how often Camel will pull for reply messages using the option. By default its 1000 millis. So to make it faster you can set it to 250 millis to pull 4 times per second as shown:

from(xxx) .inOut().to("activemq:queue:foo?replyTo=bar&receiveTimeout=250") .to(yyy)

Notice this will cause the Camel to send pull requests to the message broker more frequent, and thus require more network traffic.
It is generally recommended to use temporary queues if possible.

Request-reply over JMS and using an exclusive fixed reply queue

Available as of Camel 2.9

In the previous example, Camel would anticipate the fixed reply queue named "bar" was shared, and thus it uses a to only consume reply messages which it expects. However there is a drawback doing this as JMS selectos is slower. Also the consumer on the reply queue is slower to update with new JMS selector ids. In fact it only updates when the option times out, which by default is 1 second. So in theory the reply messages could take up till about 1 sec to be detected. On the other hand if the fixed reply queue is exclusive to the Camel reply consumer, then we can avoid using the JMS selectors, and thus be more performant. In fact as fast as using temporary queues. So in Camel 2.9 onwards we introduced the option which you can configure to
to tell Camel that the reply queue is exclusive as shown in the example below:

from(xxx) .inOut().to("activemq:queue:foo?replyTo=bar?replyToType=Exclusive") .to(yyy)

Mind that the queue must be exclusive to each and every endpoint. So if you have two routes, then they each need an unique reply queue as shown in the next example:

from(xxx) .inOut().to("activemq:queue:foo?replyTo=bar?replyToType=Exclusive") .to(yyy) from(aaa) .inOut().to("activemq:queue:order?replyTo=order.reply?replyToType=Exclusive") .to(bbb)

The same applies if you run in a clustered environment. Then each node in the cluster must use an unique reply queue name. As otherwise each node in the cluster may pickup messages which was intended as a reply on another node. For clustered environments its recommended to use shared reply queues instead.

Synchronizing clocks between senders and receivers

When doing messaging between systems, its desirable that the systems have synchronized clocks. For example when sending a JMS message, then you can set a time to live value on the message. Then the receiver can inspect this value, and determine if the message is already expired, and thus drop the message instead of consume and process it. However this requires that both sender and receiver have synchronized clocks. If you are using ActiveMQ then you can use the timestamp plugin to synchronize clocks.

About time to live

Read first above about synchronized clocks.

When you do request/reply (InOut) over JMS with Camel then Camel uses a timeout on the sender side, which is default 20 seconds from the option. You can control this by setting a higher/lower value. However the time to live value is still set on the JMS message being send. So that requires the clocks to be synchronized between the systems. If they are not, then you may want to disable the time to live value being set. This is now possible using the option from Camel 2.8 onwards. So if you set this option to , then Camel does not set any time to live value when sending JMS messages. But the request timeout is still active. So for example if you do request/reply over JMS and have disabled time to live, then Camel will still use a timeout by 20 seconds (the option). That option can of course also be configured. So the two options and gives you fine grained control when doing request/reply.

When you do fire and forget (InOut) over JMS with Camel then Camel by default does not set any time to live value on the message. You can configure a value by using the option. For example to indicate a 5 sec., you set . The option can be used to force disabling the time to live, also for InOnly messaging. The option is not being used for InOnly messaging.

Enabling Transacted Consumption

A common requirement is to consume from a queue in a transaction and then process the message using the Camel route. To do this, just ensure that you set the following properties on the component/endpoint:

  • = true
  • = a Transsaction Manager - typically the

See the Transactional Client EIP pattern for further details.

Transactions and Request Reply over JMS
When using Request Reply over JMS you cannot use a single transaction; JMS will not send any messages until a commit is performed, so the server side won't receive anything at all until the transaction commits. Therefore to use Request Reply you must commit a transaction after sending the request and then use a separate transaction for receiving the response.

To address this issue the JMS component uses different properties to specify transaction use for oneway messaging and request reply messaging:

The property applies only to the InOnly message Exchange Pattern (MEP).

The property applies to the InOut(Request Reply) message Exchange Pattern (MEP).

If you want to use transactions for Request Reply(InOut MEP), you must set .

Using JMSReplyTo for late replies

When using Camel as a JMS listener, it sets an Exchange property with the value of the ReplyTo object, having the key . You can obtain this as follows:

Destination replyDestination = exchange.getIn().getHeader(JmsConstants.JMS_REPLY_DESTINATION, Destination.class);

And then later use it to send a reply using regular JMS or Camel.

JmsEndpoint endpoint = JmsEndpoint.newInstance(replyDestination, activeMQComponent); template.sendBody(endpoint, "Here is the late reply.");

A different solution to sending a reply is to provide the object in the same Exchange property when sending. Camel will then pick up this property and use it for the real destination. The endpoint URI must include a dummy destination, however. For example:

template.send("activemq:queue:dummy, new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(JmsConstants.JMS_DESTINATION, replyDestination); exchange.getIn().setBody("Here is the late reply."); } }

Using a request timeout

In the sample below we send a Request Reply style message Exchange (we use the method = ) to the slow queue for further processing in Camel and we wait for a return reply:

Object out = template.requestBody("activemq:queue:slow?requestTimeout=5000", "Hello World");

Samples

JMS is used in many examples for other components as well. But we provide a few samples below to get started.

Receiving from JMS

In the following sample we configure a route that receives JMS messages and routes the message to a POJO:

from("jms:queue:foo"). to("bean:myBusinessLogic");

You can of course use any of the EIP patterns so the route can be context based. For example, here's how to filter an order topic for the big spenders:

from("jms:topic:OrdersTopic"). filter().method("myBean", "isGoldCustomer"). to("jms:queue:BigSpendersQueue");

Sending to a JMS

In the sample below we poll a file folder and send the file content to a JMS topic. As we want the content of the file as a instead of a , we need to convert the body to a :

from("file:). convertBodyTo(String.class). to("jms:topic:OrdersTopic");

Using Annotations

Camel also has annotations so you can use POJO Consuming and POJO Producing.

Spring DSL sample

The preceding examples use the Java DSL. Camel also supports Spring XML DSL. Here is the big spender sample using Spring DSL:

<route><from uri="jms:topic:OrdersTopic"/><filter><method bean="myBean" method="isGoldCustomer"/><to uri="jms:queue:BigSpendersQueue"/></filter></route>

Other samples

JMS appears in many of the examples for other components and EIP patterns, as well in this Camel documentation. So feel free to browse the documentation. If you have time, check out the this tutorial that uses JMS but focuses on how well Spring Remoting and Camel works together Tutorial-JmsRemoting.

Using JMS as a Dead Letter Queue storing Exchange

Normally, when using JMS as the transport, it only transfers the body and headers as the payload. If you want to use JMS with a Dead Letter Channel, using a JMS queue as the Dead Letter Queue, then normally the caused Exception is not stored in the JMS message. You can, however, use the transferExchange option on the JMS dead letter queue to instruct Camel to store the entire Exchange in the queue as a that holds a . This allows you to consume from the Dead Letter Queue and retrieve the caused exception from the Exchange property with the key . The demo below illustrates this:

errorHandler(deadLetterChannel("jms:queue:dead?transferExchange=true"));

Then you can consume from the JMS queue and analyze the problem:

from("jms:queue:dead").to("bean:myErrorAnalyzer"); String body = exchange.getIn().getBody(); Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); String problem = cause.getMessage();

Using JMS as a Dead Letter Channel storing error only

You can use JMS to store the cause error message or to store a custom body, which you can initialize yourself. The following example uses the Message Translator EIP to do a transformation on the failed exchange before it is moved to the JMS dead letter queue:

errorHandler(deadLetterChannel("seda:dead")); from("seda:dead").transform(exceptionMessage()).to("jms:queue:dead");

Here we only store the original cause error message in the transform. You can, however, use any Expression to send whatever you like. For example, you can invoke a method on a Bean or use a custom processor.

Sending an InOnly message and keeping the JMSReplyTo header

When sending to a JMS destination using camel-jms the producer will use the MEP to detect if its InOnly or InOut messaging. However there can be times where you want to send an InOnly message but keeping the JMSReplyTo header. To do so you have to instruct Camel to keep it, otherwise the JMSReplyTo header will be dropped.

For example to send an InOnly message to the foo queue, but with a JMSReplyTo with bar queue you can do as follows:

template.send("activemq:queue:foo?preserveMessageQos=true", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("World"); exchange.getIn().setHeader("JMSReplyTo", "bar"); } });

Notice we use to instruct Camel to keep the JMSReplyTo header.

Setting JMS provider options on the destination

Some JMS providers, like IBM's WebSphere MQ need options to be set on the JMS destination. For example, you may need to specify the targetClient option. Since targetClient is a WebSphere MQ option and not a Camel URI option, you need to set that on the JMS destination name like so:

... .setHeader("CamelJmsDestinationName", constant("queue:)) .to("wmq:queue:MY_QUEUE?useMessageIDAsCorrelationID=true");

Some versions of WMQ won't accept this option on the destination name and you will get an exception like:

com.ibm.msg.client.jms.DetailedJMSException: JMSCC0005: The specified value 'MY_QUEUE?targetClient=1' is not allowed for 'XMSC_DESTINATION_NAME'

A workaround is to use a custom DestinationResolver:

JmsComponent wmq = new JmsComponent(connectionFactory); wmq.setDestinationResolver(new DestinationResolver(){ public Destination resolveDestinationName(Session session, String destinationName, boolean pubSubDomain) throws JMSException { MQQueueSession wmqSession = (MQQueueSession) session; return wmqSession.createQueue("queue: + destinationName + "?targetClient=1"); } });

See Also

Sours: https://people.apache.org/~dkulp/camel/jms.html

Jms camel

/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.*/packageorg.apache.camel.component.jms;importjava.util.Map;importjava.util.concurrent.ExecutorService;importjavax.jms.ConnectionFactory;importjavax.jms.ExceptionListener;importjavax.jms.Message;importjavax.jms.Session;importorg.apache.camel.CamelContext;importorg.apache.camel.Endpoint;importorg.apache.camel.LoggingLevel;importorg.apache.camel.impl.HeaderFilterStrategyComponent;importorg.apache.camel.spi.Metadata;importorg.apache.camel.util.ObjectHelper;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.BeansException;importorg.springframework.context.ApplicationContext;importorg.springframework.context.ApplicationContextAware;importorg.springframework.core.task.TaskExecutor;importorg.springframework.jms.connection.JmsTransactionManager;importorg.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter;importorg.springframework.jms.core.JmsOperations;importorg.springframework.jms.support.converter.MessageConverter;importorg.springframework.jms.support.destination.DestinationResolver;importorg.springframework.transaction.PlatformTransactionManager;importorg.springframework.util.ErrorHandler;import staticorg.apache.camel.util.ObjectHelper.removeStartingCharacters;/** * A <ahref="http://activemq.apache.org/jms.html">JMS Component</a> * * @version*/publicclassJmsComponentextendsHeaderFilterStrategyComponentimplementsApplicationContextAware {privatestaticfinalLoggerLOG=LoggerFactory.getLogger(JmsComponent.class);privatestaticfinalStringKEY_FORMAT_STRATEGY_PARAM="jmsKeyFormatStrategy";privateExecutorService asyncStartStopExecutorService;privateApplicationContext applicationContext;@Metadata(label="advanced", description="To use a shared JMS configuration")privateJmsConfiguration configuration;@Metadata(label="advanced", description="To use a custom QueueBrowseStrategy when browsing queues")privateQueueBrowseStrategy queueBrowseStrategy;@Metadata(label="advanced", description="To use the given MessageCreatedStrategy which are invoked when Camel creates new instances"+" of javax.jms.Message objects when Camel is sending a JMS message.")privateMessageCreatedStrategy messageCreatedStrategy;publicJmsComponent() {super(JmsEndpoint.class); }publicJmsComponent(Class<? extends Endpoint>endpointClass) {super(endpointClass); }publicJmsComponent(CamelContextcontext) {super(context, JmsEndpoint.class); }publicJmsComponent(CamelContextcontext, Class<? extends Endpoint>endpointClass) {super(context, endpointClass); }publicJmsComponent(JmsConfigurationconfiguration) {this();this.configuration = configuration; }/** * Static builder method*/publicstaticJmsComponentjmsComponent() {returnnewJmsComponent(); }/** * Static builder method*/publicstaticJmsComponentjmsComponent(JmsConfigurationconfiguration) {returnnewJmsComponent(configuration); }/** * Static builder method*/publicstaticJmsComponentjmsComponent(ConnectionFactoryconnectionFactory) {return jmsComponent(newJmsConfiguration(connectionFactory)); }/** * Static builder method*/publicstaticJmsComponentjmsComponentClientAcknowledge(ConnectionFactoryconnectionFactory) {JmsConfiguration template =newJmsConfiguration(connectionFactory); template.setAcknowledgementMode(Session.CLIENT_ACKNOWLEDGE);return jmsComponent(template); }/** * Static builder method*/publicstaticJmsComponentjmsComponentAutoAcknowledge(ConnectionFactoryconnectionFactory) {JmsConfiguration template =newJmsConfiguration(connectionFactory); template.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);return jmsComponent(template); }publicstaticJmsComponentjmsComponentTransacted(ConnectionFactoryconnectionFactory) {JmsTransactionManager transactionManager =newJmsTransactionManager(); transactionManager.setConnectionFactory(connectionFactory);return jmsComponentTransacted(connectionFactory, transactionManager); }@SuppressWarnings("deprecation")publicstaticJmsComponentjmsComponentTransacted(ConnectionFactoryconnectionFactory,PlatformTransactionManagertransactionManager) {JmsConfiguration template =newJmsConfiguration(connectionFactory); template.setTransactionManager(transactionManager); template.setTransacted(true); template.setTransactedInOut(true);return jmsComponent(template); }// Properties// -------------------------------------------------------------------------publicJmsConfigurationgetConfiguration() {if (configuration ==null) { configuration = createConfiguration();// If we are being configured with spring...if (applicationContext !=null) {if (isAllowAutoWiredConnectionFactory()) {Map<String, ConnectionFactory> beansOfTypeConnectionFactory = applicationContext.getBeansOfType(ConnectionFactory.class);if (!beansOfTypeConnectionFactory.isEmpty()) {ConnectionFactory cf = beansOfTypeConnectionFactory.values().iterator().next(); configuration.setConnectionFactory(cf); } }if (isAllowAutoWiredDestinationResolver()) {Map<String, DestinationResolver> beansOfTypeDestinationResolver = applicationContext.getBeansOfType(DestinationResolver.class);if (!beansOfTypeDestinationResolver.isEmpty()) {DestinationResolver destinationResolver = beansOfTypeDestinationResolver.values().iterator().next(); configuration.setDestinationResolver(destinationResolver); } } } }return configuration; }/** * Subclasses can override to prevent the jms configuration from being * setup to use an auto-wired the connection factory that's found in the spring * application context. * * @return true by default*/publicbooleanisAllowAutoWiredConnectionFactory() {returntrue; }/** * Subclasses can override to prevent the jms configuration from being * setup to use an auto-wired the destination resolved that's found in the spring * application context. * * @return true by default*/publicbooleanisAllowAutoWiredDestinationResolver() {returntrue; }/** * To use a shared JMS configuration*/publicvoidsetConfiguration(JmsConfigurationconfiguration) {this.configuration = configuration; }/** * Specifies whether the consumer accept messages while it is stopping. * You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages * enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected, * and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message * may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option.*/@Metadata(label="consumer,advanced",description="Specifies whether the consumer accept messages while it is stopping."+" You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages"+" enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected,"+" and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message"+" may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option.")publicvoidsetAcceptMessagesWhileStopping(booleanacceptMessagesWhileStopping) { getConfiguration().setAcceptMessagesWhileStopping(acceptMessagesWhileStopping); }/** * Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow * the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfiguration#isAcceptMessagesWhileStopping * is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by * default in the regular JMS consumers but to enable for reply managers you must enable this flag.*/@Metadata(label="consumer,advanced",description="Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow "+" the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfiguration#isAcceptMessagesWhileStopping"+" is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by"+" default in the regular JMS consumers but to enable for reply managers you must enable this flag.")publicvoidsetAllowReplyManagerQuickStop(booleanallowReplyManagerQuickStop) { getConfiguration().setAllowReplyManagerQuickStop(allowReplyManagerQuickStop); }/** * The JMS acknowledgement mode defined as an Integer. * Allows you to set vendor-specific extensions to the acknowledgment mode. * For the regular modes, it is preferable to use the acknowledgementModeName instead.*/@Metadata(label="consumer",description="The JMS acknowledgement mode defined as an Integer. Allows you to set vendor-specific extensions to the acknowledgment mode."+"For the regular modes, it is preferable to use the acknowledgementModeName instead.")publicvoidsetAcknowledgementMode(intconsumerAcknowledgementMode) { getConfiguration().setAcknowledgementMode(consumerAcknowledgementMode); }/** * Enables eager loading of JMS properties as soon as a message is loaded * which generally is inefficient as the JMS properties may not be required * but sometimes can catch early any issues with the underlying JMS provider * and the use of JMS properties*/@Metadata(label="consumer,advanced",description="Enables eager loading of JMS properties as soon as a message is loaded"+" which generally is inefficient as the JMS properties may not be required"+" but sometimes can catch early any issues with the underlying JMS provider"+" and the use of JMS properties")publicvoidsetEagerLoadingOfProperties(booleaneagerLoadingOfProperties) { getConfiguration().setEagerLoadingOfProperties(eagerLoadingOfProperties); }/** * The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE*/@Metadata(defaultValue="AUTO_ACKNOWLEDGE", label="consumer", enums="SESSION_TRANSACTED,CLIENT_ACKNOWLEDGE,AUTO_ACKNOWLEDGE,DUPS_OK_ACKNOWLEDGE",description="The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE")publicvoidsetAcknowledgementModeName(StringconsumerAcknowledgementMode) { getConfiguration().setAcknowledgementModeName(consumerAcknowledgementMode); }/** * Specifies whether the consumer container should auto-startup.*/@Metadata(label="consumer", defaultValue="true",description="Specifies whether the consumer container should auto-startup.")publicvoidsetAutoStartup(booleanautoStartup) { getConfiguration().setAutoStartup(autoStartup); }/** * Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details.*/@Metadata(label="consumer",description="Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details.")publicvoidsetCacheLevel(intcacheLevel) { getConfiguration().setCacheLevel(cacheLevel); }/** * Sets the cache level by name for the underlying JMS resources. * Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION. * The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information.*/@Metadata(defaultValue="CACHE_AUTO", label="consumer", enums="CACHE_AUTO,CACHE_CONNECTION,CACHE_CONSUMER,CACHE_NONE,CACHE_SESSION",description="Sets the cache level by name for the underlying JMS resources."+" Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION."+" The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information.")publicvoidsetCacheLevelName(StringcacheName) { getConfiguration().setCacheLevelName(cacheName); }/** * Sets the cache level by name for the reply consumer when doing request/reply over JMS. * This option only applies when using fixed reply queues (not temporary). * Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. * And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere * may require to set the replyToCacheLevelName=CACHE_NONE to work. * Note: If using temporary queues then CACHE_NONE is not allowed, * and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION.*/@Metadata(label="producer,advanced", enums="CACHE_AUTO,CACHE_CONNECTION,CACHE_CONSUMER,CACHE_NONE,CACHE_SESSION",description="Sets the cache level by name for the reply consumer when doing request/reply over JMS."+" This option only applies when using fixed reply queues (not temporary)."+" Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName."+" And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere"+" may require to set the replyToCacheLevelName=CACHE_NONE to work."+" Note: If using temporary queues then CACHE_NONE is not allowed,"+" and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION.")publicvoidsetReplyToCacheLevelName(StringcacheName) { getConfiguration().setReplyToCacheLevelName(cacheName); }/** * Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance. * It is typically only required for durable topic subscriptions. * <p/> * If using Apache ActiveMQ you may prefer to use Virtual Topics instead.*/@Metadata(description="Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance."+" It is typically only required for durable topic subscriptions."+" If using Apache ActiveMQ you may prefer to use Virtual Topics instead.")publicvoidsetClientId(StringconsumerClientId) { getConfiguration().setClientId(consumerClientId); }/** * Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). * See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. * <p/> * When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number * of concurrent consumers on the reply message listener.*/@Metadata(defaultValue="1", label="consumer",description="Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS)."+" See also the maxMessagesPerTask option to control dynamic scaling up/down of threads."+" When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number"+" of concurrent consumers on the reply message listener.")publicvoidsetConcurrentConsumers(intconcurrentConsumers) { getConfiguration().setConcurrentConsumers(concurrentConsumers); }/** * Specifies the default number of concurrent consumers when doing request/reply over JMS. * See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.*/@Metadata(defaultValue="1", label="producer",description="Specifies the default number of concurrent consumers when doing request/reply over JMS."+" See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.")publicvoidsetReplyToConcurrentConsumers(intconcurrentConsumers) { getConfiguration().setReplyToConcurrentConsumers(concurrentConsumers); }/** * The connection factory to be use. A connection factory must be configured either on the component or endpoint.*/@Metadata(description="The connection factory to be use. A connection factory must be configured either on the component or endpoint.")publicvoidsetConnectionFactory(ConnectionFactoryconnectionFactory) { getConfiguration().setConnectionFactory(connectionFactory); }/** * Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.*/@Metadata(label="security", secret=true, description="Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.")publicvoidsetUsername(Stringusername) { getConfiguration().setUsername(username); }/** * Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.*/@Metadata(label="security", secret=true, description="Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.")publicvoidsetPassword(Stringpassword) { getConfiguration().setPassword(password); }/** * Specifies whether persistent delivery is used by default.*/@Metadata(defaultValue="true", label="producer",description="Specifies whether persistent delivery is used by default.")publicvoidsetDeliveryPersistent(booleandeliveryPersistent) { getConfiguration().setDeliveryPersistent(deliveryPersistent); }/** * Specifies the delivery mode to be used. Possible values are * Possibles values are those defined by javax.jms.DeliveryMode. * NON_PERSISTENT = 1 and PERSISTENT = 2.*/@Metadata(label="producer", enums="1,2",description="Specifies the delivery mode to be used."+" Possibles values are those defined by javax.jms.DeliveryMode."+" NON_PERSISTENT = 1 and PERSISTENT = 2.")publicvoidsetDeliveryMode(IntegerdeliveryMode) { getConfiguration().setDeliveryMode(deliveryMode); }/** * The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well.*/@Metadata(description="The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well.")publicvoidsetDurableSubscriptionName(StringdurableSubscriptionName) { getConfiguration().setDurableSubscriptionName(durableSubscriptionName); }/** * Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions.*/@Metadata(label="advanced",description="Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions.")
Sours: https://github.com/Talend/apache-camel/blob/master/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsComponent.java
Spring Boot with Camel ActiveMQ Topic Example - JMS Topic VS Queue

Apache Camel - Message Queues



Most of the integration projects use messaging as it helps in creating loosely coupled application architecture. Messaging can be either synchronous or asynchronous. JMS supports both point-to-point and publish-subscribe models. You use a Queue for point-to-point and Topic for a publish-subscribe model. On a Java platform, JMS - Java Messaging Service provides an interface to a messaging server. Apache activeMQ is one such open source JMS provider. Camel does not ship with a JMS provider; however, it can be configured to use activeMQ. To use this component, you need to include the following jars in your project - activemq, camel-spring, and camel-jms.

The following code snippet shows how to configure Camel for activeMQ.

<bean id = "jms" class = "org.apache.camel.component.jms.JmsComponent"> <property name = "connectionFactory"> <bean class="org.apache.activemq.ActiveMQConnectionFactory"> <property name = "orderQueue" value = "tcp://localhost:61000" /> </bean> </property> </bean>

Here, the Camel application will start listening to a queue called orderQueue. The queue itself is set up in the activeMQ messaging server running on the local host and listing to port 61000. Once this is done, your application can send or receive message to this queue from any of the endpoints defined in your application.

Finally, it is time now to put everything together in a project to get a deeper understanding of how Camel applications are created.

Sours: https://www.tutorialspoint.com/apache_camel/apache_camel_message_queues.htm

Now discussing:

JMS

clientId (common)

Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions. If using Apache ActiveMQ you may prefer to use Virtual Topics instead.

String

connectionFactory (common)

The connection factory to be use. A connection factory must be configured either on the component or endpoint.

ConnectionFactory

disableReplyTo (common)

Specifies whether Camel ignores the JMSReplyTo header in messages. If true, Camel does not send a reply back to the destination specified in the JMSReplyTo header. You can use this option if you want Camel to consume from a route and you do not want Camel to automatically send back a reply message because another component in your code handles the reply message. You can also use this option if you want to use Camel as a proxy between different message brokers and you want to route message from one system to another.

false

boolean

durableSubscriptionName (common)

The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well.

String

jmsMessageType (common)

Allows you to force the use of a specific javax.jms.Message implementation for sending JMS messages. Possible values are: Bytes, Map, Object, Stream, Text. By default, Camel would determine which JMS message type to use from the In body type. This option allows you to specify it. There are 5 enums and the value can be one of: Bytes, Map, Object, Stream, Text

JmsMessageType

replyTo (common)

Provides an explicit ReplyTo destination (overrides any incoming value of Message.getJMSReplyTo() in consumer).

String

testConnectionOnStartup (common)

Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well.

false

boolean

acknowledgementModeName (consumer)

The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE. There are 4 enums and the value can be one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE

AUTO_ACKNOWLEDGE

String

artemisConsumerPriority (consumer)

Consumer priorities allow you to ensure that high priority consumers receive messages while they are active. Normally, active consumers connected to a queue receive messages from it in a round-robin fashion. When consumer priorities are in use, messages are delivered round-robin if multiple active consumers exist with the same high priority. Messages will only going to lower priority consumers when the high priority consumers do not have credit available to consume the message, or those high priority consumers have declined to accept the message (for instance because it does not meet the criteria of any selectors associated with the consumer).

int

asyncConsumer (consumer)

Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue, while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100% strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer will pickup the next message from the JMS queue. Note if transacted has been enabled, then asyncConsumer=true does not run asynchronously, as transaction must be executed synchronously (Camel 3.0 may support async transactions).

false

boolean

autoStartup (consumer)

Specifies whether the consumer container should auto-startup.

true

boolean

cacheLevel (consumer)

Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details.

int

cacheLevelName (consumer)

Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information. There are 5 enums and the value can be one of: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, CACHE_SESSION

CACHE_AUTO

String

concurrentConsumers (consumer)

Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener.

1

int

maxConcurrentConsumers (consumer)

Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener.

int

replyToDeliveryPersistent (consumer)

Specifies whether to use persistent delivery by default for replies.

true

boolean

selector (consumer)

Sets the JMS selector to use

String

subscriptionDurable (consumer)

Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well.

false

boolean

subscriptionName (consumer)

Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client’s JMS client id. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription, except for a shared subscription (which requires JMS 2.0).

String

subscriptionShared (consumer)

Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable, so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker.

false

boolean

acceptMessagesWhileStopping (consumer)

Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected, and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option.

false

boolean

allowReplyManagerQuickStop (consumer)

Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfiguration#isAcceptMessagesWhileStopping is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag.

false

boolean

consumerType (consumer)

The consumer type to use, which can be one of: Simple, Default, or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer, Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified, the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use. There are 3 enums and the value can be one of: Simple, Default, Custom

Default

ConsumerType

defaultTaskExecutorType (consumer)

Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer, for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring’s SimpleAsyncTaskExecutor) or ThreadPool (uses Spring’s ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set, it defaults to the previous behaviour, which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers. There are 2 enums and the value can be one of: ThreadPool, SimpleAsync

DefaultTaskExecutorType

eagerLoadingOfProperties (consumer)

Enables eager loading of JMS properties and payload as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties. See also the option eagerPoisonBody.

false

boolean

eagerPoisonBody (consumer)

If eagerLoadingOfProperties is enabled and the JMS message payload (JMS body or JMS properties) is poison (cannot be read/mapped), then set this text as the message body instead so the message can be processed (the cause of the poison are already stored as exception on the Exchange). This can be turned off by setting eagerPoisonBody=false. See also the option eagerLoadingOfProperties.

Poison JMS message due to ${exception.message}

String

exposeListenerSession (consumer)

Specifies whether the listener session should be exposed when consuming messages.

false

boolean

replyToSameDestinationAllowed (consumer)

Whether a JMS consumer is allowed to send a reply message to the same destination that the consumer is using to consume from. This prevents an endless loop by consuming and sending back the same message to itself.

false

boolean

taskExecutor (consumer)

Allows you to specify a custom task executor for consuming messages.

TaskExecutor

deliveryDelay (producer)

Sets delivery delay to use for send calls for JMS. This option requires JMS 2.0 compliant broker.

-1

long

deliveryMode (producer)

Specifies the delivery mode to be used. Possible values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2. There are 2 enums and the value can be one of: 1, 2

Integer

deliveryPersistent (producer)

Specifies whether persistent delivery is used by default.

true

boolean

explicitQosEnabled (producer)

Set if the deliveryMode, priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring’s JmsTemplate. The deliveryMode, priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option, which operates at message granularity, reading QoS properties exclusively from the Camel In message headers.

false

Boolean

formatDateHeadersToIso8601 (producer)

Sets whether JMS date properties should be formatted according to the ISO 8601 standard.

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

preserveMessageQos (producer)

Set to true, if you want to send message using the QoS settings specified on the message, instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority, JMSDeliveryMode, and JMSExpiration. You can provide all or only some of them. If not provided, Camel will fall back to use the values from the endpoint instead. So, when using this option, the headers override the values from the endpoint. The explicitQosEnabled option, by contrast, will only use options set on the endpoint, and not values from the message header.

false

boolean

priority (producer)

Values greater than 1 specify the message priority when sending (where 1 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect. There are 9 enums and the value can be one of: 1, 2, 3, 4, 5, 6, 7, 8, 9

4

int

replyToConcurrentConsumers (producer)

Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.

1

int

replyToMaxConcurrentConsumers (producer)

Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads.

int

replyToOnTimeoutMaxConcurrent​Consumers (producer)

Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS.

1

int

replyToOverride (producer)

Provides an explicit ReplyTo destination in the JMS message, which overrides the setting of replyTo. It is useful if you want to forward the message to a remote Queue and receive the reply message from the ReplyTo destination.

String

replyToType (producer)

Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary, Shared, or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured, then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details, and especially the notes about the implications if running in a clustered environment, and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive. There are 3 enums and the value can be one of: Temporary, Shared, Exclusive

ReplyToType

requestTimeout (producer)

The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value, and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option.

20000

long

timeToLive (producer)

When sending messages, specifies the time-to-live of the message (in milliseconds).

-1

long

allowAdditionalHeaders (producer)

This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma, and use as suffix for wildcard matching.

String

allowNullBody (producer)

Whether to allow sending messages with no body. If this option is false and the message body is null, then an JMSException is thrown.

true

boolean

alwaysCopyMessage (producer)

If true, Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations, such as when a replyToDestinationSelectorName is set (incidentally, Camel will set the alwaysCopyMessage option to true, if a replyToDestinationSelectorName is set)

false

boolean

correlationProperty (producer)

When using InOut exchange pattern use this JMS property instead of JMSCorrelationID JMS property to correlate messages. If set messages will be correlated solely on the value of this property JMSCorrelationID property will be ignored and not set by Camel.

String

disableTimeToLive (producer)

Use this option to force disabling time to live. For example when you do request/reply over JMS, then Camel will by default use the requestTimeout value as time to live on the message being sent. The problem is that the sender and receiver systems have to have their clocks synchronized, so they are in sync. This is not always so easy to archive. So you can use disableTimeToLive=true to not set a time to live value on the sent message. Then the message will not expire on the receiver system. See below in section About time to live for more details.

false

boolean

forceSendOriginalMessage (producer)

When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received.

false

boolean

includeSentJMSMessageID (producer)

Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination.

false

boolean

replyToCacheLevelName (producer)

Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed, and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION. There are 5 enums and the value can be one of: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, CACHE_SESSION

String

replyToDestinationSelectorName (producer)

Sets the JMS Selector using the fixed name to be used so you can filter out your own replies from the others when using a shared queue (that is, if you are not using a temporary reply queue).

String

streamMessageTypeEnabled (producer)

Sets whether StreamMessage type is enabled or not. Message payloads of streaming kind such as files, InputStream, etc will either by sent as BytesMessage or StreamMessage. This option controls which kind will be used. By default BytesMessage is used which enforces the entire message payload to be read into memory. By enabling this option the message payload is read into memory in chunks and each chunk is then written to the StreamMessage until no more data.

false

boolean

allowAutoWiredConnection​Factory (advanced)

Whether to auto-discover ConnectionFactory from the registry, if no connection factory has been configured. If only one instance of ConnectionFactory is found then it will be used. This is enabled by default.

true

boolean

allowAutoWiredDestination​Resolver (advanced)

Whether to auto-discover DestinationResolver from the registry, if no destination resolver has been configured. If only one instance of DestinationResolver is found then it will be used. This is enabled by default.

true

boolean

allowSerializedHeaders (advanced)

Controls whether or not to include serialized headers. Applies only when transferExchange is true. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level.

false

boolean

artemisStreamingEnabled (advanced)

Whether optimizing for Apache Artemis streaming mode.

true

boolean

asyncStartListener (advanced)

Whether to startup the JmsConsumer message listener asynchronously, when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker, then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true, you will let routes startup, while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used, then beware that if the connection could not be established, then an exception is logged at WARN level, and the consumer will not be able to receive messages; You can then restart the route to retry.

false

boolean

asyncStopListener (advanced)

Whether to stop the JmsConsumer message listener asynchronously, when stopping a route.

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

configuration (advanced)

To use a shared JMS configuration

JmsConfiguration

destinationResolver (advanced)

A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example, to lookup the real destination in a JNDI registry).

DestinationResolver

errorHandler (advanced)

Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level, if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure, than having to code a custom errorHandler.

ErrorHandler

exceptionListener (advanced)

Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions.

ExceptionListener

idleConsumerLimit (advanced)

Specify the limit for the number of consumers that are allowed to be idle at any given time.

1

int

idleTaskExecutionLimit (advanced)

Specifies the limit for idle executions of a receive task, not having received any message within its execution. If this limit is reached, the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring.

1

int

includeAllJMSXProperties (advanced)

Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID, and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply.

false

boolean

jmsKeyFormatStrategy (advanced)

Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the # notation. There are 2 enums and the value can be one of: default, passthrough

JmsKeyFormatStrategy

mapJmsMessage (advanced)

Specifies whether Camel should auto map the received JMS message to a suited payload type, such as javax.jms.TextMessage to a String etc.

true

boolean

maxMessagesPerTask (advanced)

The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max), then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required.

-1

int

messageConverter (advanced)

To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message.

MessageConverter

messageCreatedStrategy (advanced)

To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message.

MessageCreatedStrategy

messageIdEnabled (advanced)

When sending, specifies whether message IDs should be added. This is just an hint to the JMS broker. If the JMS provider accepts this hint, these messages must have the message ID set to null; if the provider ignores the hint, the message ID must be set to its normal unique value.

true

boolean

messageListenerContainer​Factory (advanced)

Registry ID of the MessageListenerContainerFactory used to determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use to consume messages. Setting this will automatically set consumerType to Custom.

MessageListenerContainerFactory

messageTimestampEnabled (advanced)

Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker. If the JMS provider accepts this hint, these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value.

true

boolean

pubSubNoLocal (advanced)

Specifies whether to inhibit the delivery of messages published by its own connection.

false

boolean

queueBrowseStrategy (advanced)

To use a custom QueueBrowseStrategy when browsing queues

QueueBrowseStrategy

receiveTimeout (advanced)

The timeout for receiving messages (in milliseconds).

1000

long

recoveryInterval (advanced)

Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds. The default is 5000 ms, that is, 5 seconds.

5000

long

requestTimeoutCheckerInterval (advanced)

Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs, then you can lower this interval, to check more frequently. The timeout is determined by the option requestTimeout.

1000

long

synchronous (advanced)

Sets whether synchronous processing should be strictly used

false

boolean

transferException (advanced)

If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side, then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel, the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example, using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled, this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer. Use this with caution as the data is using Java Object serialization and requires the received to be able to deserialize the data at Class level, which forces a strong coupling between the producers and consumer!

false

boolean

transferExchange (advanced)

You can transfer the exchange over the wire instead of just the body and headers. The following fields are transferred: In body, Out body, Fault body, In headers, Out headers, Fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. You must enable this option on both the producer and consumer side, so Camel knows the payloads is an Exchange and not a regular payload. Use this with caution as the data is using Java Object serialization and requires the receiver to be able to deserialize the data at Class level, which forces a strong coupling between the producers and consumers having to use compatible Camel versions!

false

boolean

useMessageIDAsCorrelationID (advanced)

Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages.

false

boolean

waitForProvisionCorrelationTo​BeUpdatedCounter (advanced)

Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled.

50

int

waitForProvisionCorrelationTo​BeUpdatedThreadSleepingTime (advanced)

Interval in millis to sleep each time while waiting for provisional correlation id to be updated.

100

long

headerFilterStrategy (filter)

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

HeaderFilterStrategy

errorHandlerLoggingLevel (logging)

Allows to configure the default errorHandler logging level for logging uncaught exceptions. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF

WARN

LoggingLevel

errorHandlerLogStackTrace (logging)

Allows to control whether stacktraces should be logged or not, by the default errorHandler.

true

boolean

password (security)

Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.

String

username (security)

Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory.

String

transacted (transaction)

Specifies whether to use transacted mode

false

boolean

transactedInOut (transaction)

Specifies whether InOut operations (request reply) default to using transacted mode If this flag is set to true, then Spring JmsTemplate will have sessionTransacted set to true, and the acknowledgeMode as transacted on the JmsTemplate used for InOut operations. Note from Spring JMS: that within a JTA transaction, the parameters passed to createQueue, createTopic methods are not taken into account. Depending on the Java EE transaction context, the container makes its own decisions on these values. Analogously, these parameters are not taken into account within a locally managed transaction either, since Spring JMS operates on an existing JMS Session in this case. Setting this flag to true will use a short local JMS transaction when running outside of a managed transaction, and a synchronized local JMS transaction in case of a managed transaction (other than an XA transaction) being present. This has the effect of a local JMS transaction being managed alongside the main transaction (which might be a native JDBC transaction), with the JMS transaction committing right after the main transaction.

false

boolean

lazyCreateTransactionManager (transaction)

If true, Camel will create a JmsTransactionManager, if there is no transactionManager injected when option transacted=true.

true

boolean

transactionManager (transaction)

The Spring transaction manager to use.

PlatformTransactionManager

transactionName (transaction)

The name of the transaction to use.

String

transactionTimeout (transaction)

The timeout value of the transaction (in seconds), if using transacted mode.

-1

int

Sours: https://camel.apache.org/components/3.11.x/jms-component.html


775 776 777 778 779