Camel Components

Spring RabbitMQ

Since Camel 3.8

Both producer and consumer are supported

The Spring RabbitMQ component allows you to produce and consume messages from RabbitMQ instances. Using the Spring RabbitMQ client.

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

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

URI format

spring-rabbitmq:exchangeName?[options]

The exchange name determines the exchange to which the produced messages will be sent to. In the case of consumers, the exchange name determines the exchange the queue will be bound to.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The Spring RabbitMQ component supports the following options which are listed below.

Name Description Default Type

amqpAdmin (common)

Autowired The AmqpAdmin, such as a RabbitAdmin, that declares the exchanges, queues and bindings when auto-declaring (autoDeclare, autoDeclareProducer). The component uses the single AmqpAdmin in the registry when there is one; otherwise Camel creates a RabbitAdmin on the connection factory of the endpoint.

AmqpAdmin

connectionFactory (common)

Autowired The Spring AMQP ConnectionFactory to connect to RabbitMQ with, such as a CachingConnectionFactory. It must be set on the component or the endpoint; the component uses the single ConnectionFactory in the registry when there is one.

ConnectionFactory

testConnectionOnStartup (common)

Whether the consumers and producers test the connection to RabbitMQ when they start, by opening a connection with the connection factory: if that fails, the start fails, so that Camel does not start without a connection to RabbitMQ. Without it, a consumer starts while RabbitMQ is not available and keeps trying to connect.

false

boolean

autoDeclare (consumer)

Whether the consumer declares the exchange (of the exchangeType), its queues and their bindings to the exchange with the routing key, and the dead letter exchange and queue when they are configured, when it starts, and again on every new connection of the connection factory (except with a CachingConnectionFactory in CONNECTION cache mode). The exchange and the queues are durable and not auto-delete, unless the args option says otherwise. The amqpAdmin of the component declares them, else a RabbitAdmin that Camel creates.

true

boolean

autoStartup (consumer)

Whether the consumer starts its listener container, and so consumes messages, when it starts. If false, the listener container is started later, when the consumer is resumed.

true

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

deadLetterExchange (consumer)

The name of the dead letter exchange. Auto-declare (autoDeclare, autoDeclareProducer) declares it, of the deadLetterExchangeType, and declares the queues with it as their x-dead-letter-exchange argument, so that RabbitMQ dead-letters to it the messages that are rejected without requeue (see rejectAndDontRequeue) or that expire. Without auto-declare, this option is not used.

String

deadLetterExchangeType (consumer)

The type of the dead letter exchange that auto-declare declares: direct, fanout, headers or topic.

Enum values:

  • direct

  • fanout

  • headers

  • topic

direct

String

deadLetterQueue (consumer)

The name of the dead letter queue, which auto-declare declares as a durable queue and binds to the deadLetterExchange with the deadLetterRoutingKey. Only used together with deadLetterExchange.

String

deadLetterRoutingKey (consumer)

The routing key for the dead letter exchange (the x-dead-letter-routing-key of the consumer queue). An auto-declared deadLetterQueue is bound to the dead letter exchange with this routing key: it is required for a direct or topic dead letter exchange, and not needed for a fanout or headers one.

String

maximumRetryAttempts (consumer)

How many times the consumer retries a message that the route failed to process. The retries run in the listener container, without a redelivery by RabbitMQ. The first try is not counted, so 5 means up to 6 tries; 0 or less means no retry. After the last try, rejectAndDontRequeue decides what happens to the message.

5

int

rejectAndDontRequeue (consumer)

What the consumer does with a message that the route still failed to process after the retries. If true, it rejects the message without requeue, so that RabbitMQ dead-letters it when the queue has a dead letter exchange (see deadLetterExchange), and discards it otherwise. If false, Spring AMQP logs and drops the message: it is acknowledged (with acknowledgeMode AUTO), not requeued.

true

boolean

retryDelay (consumer)

The delay in milliseconds between the retries of a message that the route failed to process (see maximumRetryAttempts), the same for every retry. A value of 0 or less does not remove the delay: the default delay of Spring, 1000 milliseconds, is used then.

1000

int

concurrentConsumers (consumer (advanced))

The number of consumers: with DMLC, the consumers per queue; with SMLC, the consumers that each consume from all the queues. With more than one consumer, the messages are not processed in order.

1

int

errorHandler (consumer (advanced))

A custom Spring ErrorHandler that the listener container calls with the exceptions that the message listener throws, such as for a message that is rejected after the retries. By default the listener container uses a ConditionalRejectingErrorHandler.

ErrorHandler

listenerContainerFactory (consumer (advanced))

To use a custom factory for creating and configuring ListenerContainer to be used by the consumer for receiving messages.

ListenerContainerFactory

maxConcurrentConsumers (consumer (advanced))

The maximum number of consumers, up to which a SimpleMessageListenerContainer (SMLC) adds consumers when the load increases. Not used with DMLC. If not set, the number of consumers stays at concurrentConsumers.

Integer

messageListenerContainerType (consumer (advanced))

The type of the Spring AMQP listener container: DMLC (DirectMessageListenerContainer) calls the route on a thread of the RabbitMQ client, with concurrentConsumers consumers per queue; SMLC (SimpleMessageListenerContainer) calls it on its own consumer threads, each consuming from all the queues, and can add consumers up to maxConcurrentConsumers.

Enum values:

  • DMLC

  • SMLC

DMLC

String

prefetchCount (consumer (advanced))

The prefetch count (basic.qos) of each consumer: how many unacknowledged messages RabbitMQ sends to a consumer at a time. A high value improves throughput; after a reconnect, up to this many messages per consumer may be delivered again. Not used with acknowledgeMode NONE.

250

int

retry (consumer (advanced))

A custom StatelessRetryOperationsInterceptor, such as one built with RetryInterceptorBuilder.stateless(), that the listener container uses to retry a message that the route failed to process. When it is set, maximumRetryAttempts, retryDelay and rejectAndDontRequeue are not used.

StatelessRetryOperationsInterceptor

shutdownTimeout (consumer (advanced))

The time to wait for workers in milliseconds after the container is stopped. If any workers are active when the shutdown signal comes they will be allowed to finish processing as long as they can finish within this timeout.

5000

long

allowNullBody (producer)

Whether to allow sending a message with a null body, which is then sent with an empty body. If false, the default message converter fails to send a null body with a MessageConversionException.

false

boolean

autoDeclareProducer (producer)

Whether the producer declares the exchange, the queues and their bindings, and the dead letter exchange and queue when they are configured, when it starts, as autoDeclare does for the consumer. Without the queues option, it declares a durable queue with a generated name: use skipDeclareQueue and skipBindQueue to declare the exchange only.

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

replyTimeout (producer)

The time in milliseconds that the producer waits for the reply to a request/reply (InOut) message, which it receives with RabbitMQ direct reply-to. When no reply arrives in time, the exchange fails with an AmqpReplyTimeoutException. 0 or a negative value waits forever: beware that every reply that never arrives then leaks memory.

30000

long

args (advanced)

The arguments of the elements that are auto-declared and of the consumers, for all the endpoints (the arg. options of an endpoint add to them), each key with the prefix of its element: exchange., queue. and binding. for the exchange, the queues and their bindings; dlq.exchange., dlq.queue. and dlq.binding. for the dead letter exchange, queue and binding; and consumer. for the consumer arguments of basic.consume. The keys durable and autoDelete of the exchange, and durable, autoDelete and exclusive of a queue, set these flags (durable is true by default, the others false); the other keys are sent as arguments, such as queue.x-message-ttl=60000 for a message TTL of 60 seconds.

Map

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

ignoreDeclarationExceptions (advanced)

Whether the RabbitAdmin that Camel creates for auto-declaring ignores the exceptions of a declaration that fails, such as of a queue that exists with other arguments, so that the start does not fail: the consumer then binds and consumes such a queue by its name. Not used when the amqpAdmin option is set.

false

boolean

messageConverter (advanced)

A custom Spring AMQP MessageConverter that converts the message body to and from the body of a RabbitMQ message (org.springframework.amqp.core.Message). The default converter turns a received message with a text content type into a String, decoded with its content encoding, and any other message into a byte array; it sends a String as text, converts any other body to a byte array with the type converters, and never serializes or deserializes Java objects.

MessageConverter

messagePropertiesConverter (advanced)

A custom MessagePropertiesConverter of this component that maps the Camel message headers to and from the MessageProperties of a RabbitMQ message (org.springframework.amqp.core.MessageProperties). The default maps the CamelSpringRabbitmq headers to the message properties, and the other headers that the header filter strategy allows to the headers of the RabbitMQ message.

MessagePropertiesConverter

headerFilterStrategy (filter)

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

HeaderFilterStrategy

Endpoint Options

The Spring RabbitMQ endpoint is configured using URI syntax:

spring-rabbitmq:exchangeName

With the following path and query parameters:

Path Parameters

Name Description Default Type

exchangeName (common)

Required The exchange name determines the exchange to which the produced messages will be sent to. In the case of consumers, the exchange name determines the exchange the queue will be bound to. Note: to use default exchange then do not use empty name, but use default instead.

String

Query Parameters

Name Description Default Type

connectionFactory (common)

The Spring AMQP ConnectionFactory to connect to RabbitMQ with, such as a CachingConnectionFactory. It must be set on the component or the endpoint; the component uses the single ConnectionFactory in the registry when there is one.

ConnectionFactory

deadLetterExchange (common)

The name of the dead letter exchange. Auto-declare (autoDeclare, autoDeclareProducer) declares it, of the deadLetterExchangeType, and declares the queues with it as their x-dead-letter-exchange argument, so that RabbitMQ dead-letters to it the messages that are rejected without requeue (see rejectAndDontRequeue) or that expire. Without auto-declare, this option is not used.

String

deadLetterExchangeType (common)

The type of the dead letter exchange that auto-declare declares: direct, fanout, headers or topic.

Enum values:

  • direct

  • fanout

  • headers

  • topic

direct

String

deadLetterQueue (common)

The name of the dead letter queue, which auto-declare declares as a durable queue and binds to the deadLetterExchange with the deadLetterRoutingKey. Only used together with deadLetterExchange.

String

deadLetterRoutingKey (common)

The routing key for the dead letter exchange (the x-dead-letter-routing-key of the consumer queue). An auto-declared deadLetterQueue is bound to the dead letter exchange with this routing key: it is required for a direct or topic dead letter exchange, and not needed for a fanout or headers one.

String

disableReplyTo (common)

Whether to ignore the reply-to of the messages. The consumer then sends no reply to a message that has a reply-to, for example because another part of the route sends the reply. The producer then sends an InOut exchange as InOnly, without waiting for a reply.

false

boolean

queues (common)

The names of the queues, separated by comma. The consumer consumes from them, and auto-declare declares them and binds them to the exchange. The producer sends to the exchange, not to the queues: it only declares them, with autoDeclareProducer. A polling consumer (pollEnrich) receives from a single queue. Without queues, the consumer consumes a queue with a generated name (spring.gen-…​), which autoDeclare declares.

String

routingKey (common)

The routing key. The producer sends the messages with it, unless the CamelSpringRabbitmqRoutingOverrideKey header is set, and auto-declare binds the queues to the exchange with it. With the default exchange, it is the name of the queue to send to. The default is empty, which suits a fanout or headers exchange.

String

testConnectionOnStartup (common)

Whether the consumers and producers test the connection to RabbitMQ when they start, by opening a connection with the connection factory: if that fails, the start fails, so that Camel does not start without a connection to RabbitMQ. Without it, a consumer starts while RabbitMQ is not available and keeps trying to connect.

false

boolean

acknowledgeMode (consumer)

How the listener container acknowledges the messages. AUTO (the default) acknowledges a message when the route processed it, and when the route failed after the retries, rejects or drops it (see rejectAndDontRequeue). MANUAL leaves it to the route, which acknowledges with basicAck on the Channel of the CamelSpringRabbitmqChannel exchange property and the CamelSpringRabbitmqDeliveryTag header. NONE consumes with auto-ack: RabbitMQ considers each message acknowledged as soon as it delivers it.

Enum values:

  • NONE

  • MANUAL

  • AUTO

AcknowledgeMode

asyncConsumer (consumer)

Whether the consumer processes the exchange asynchronously, with the asynchronous routing engine. When the route continues on another thread, the listener container then takes the next message while the previous one is still being processed, so the messages may be processed out of order, and it acknowledges the message (acknowledgeMode AUTO) before its processing is done, so that a failure is not retried or rejected but handled by the exception handler of the consumer. If false (the default), the exchange is fully processed before the next message is taken.

false

boolean

autoDeclare (consumer)

Whether the consumer declares the exchange (of the exchangeType), its queues and their bindings to the exchange with the routing key, and the dead letter exchange and queue when they are configured, when it starts, and again on every new connection of the connection factory (except with a CachingConnectionFactory in CONNECTION cache mode). The exchange and the queues are durable and not auto-delete, unless the args option says otherwise. The amqpAdmin of the component declares them, else a RabbitAdmin that Camel creates.

true

boolean

autoStartup (consumer)

Whether the consumer starts its listener container, and so consumes messages, when it starts. If false, the listener container is started later, when the consumer is resumed.

true

boolean

exchangeType (consumer)

The type of the exchange that auto-declare (autoDeclare, autoDeclareProducer) declares: direct, fanout, headers or topic.

Enum values:

  • direct

  • fanout

  • headers

  • topic

direct

String

exclusive (consumer)

Whether the consumers are exclusive (the exclusive flag of basic.consume): RabbitMQ then lets no other consumer consume from the queue. Requires concurrentConsumers 1. For an exclusive queue, use arg.queue.exclusive=true instead.

false

boolean

maximumRetryAttempts (consumer)

How many times the consumer retries a message that the route failed to process. The retries run in the listener container, without a redelivery by RabbitMQ. The first try is not counted, so 5 means up to 6 tries; 0 or less means no retry. After the last try, rejectAndDontRequeue decides what happens to the message.

5

int

noLocal (consumer)

Whether the consumers are no-local (the no-local flag of basic.consume), so that they do not receive the messages published on the same connection. RabbitMQ does not implement this flag and ignores it.

false

boolean

rejectAndDontRequeue (consumer)

What the consumer does with a message that the route still failed to process after the retries. If true, it rejects the message without requeue, so that RabbitMQ dead-letters it when the queue has a dead letter exchange (see deadLetterExchange), and discards it otherwise. If false, Spring AMQP logs and drops the message: it is acknowledged (with acknowledgeMode AUTO), not requeued.

true

boolean

retryDelay (consumer)

The delay in milliseconds between the retries of a message that the route failed to process (see maximumRetryAttempts), the same for every retry. A value of 0 or less does not remove the delay: the default delay of Spring, 1000 milliseconds, is used then.

1000

int

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

concurrentConsumers (consumer (advanced))

The number of consumers: with DMLC, the consumers per queue; with SMLC, the consumers that each consume from all the queues. With more than one consumer, the messages are not processed in order. The default is the concurrentConsumers of the component, 1.

Integer

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

maxConcurrentConsumers (consumer (advanced))

The maximum number of consumers, up to which a SimpleMessageListenerContainer (SMLC) adds consumers when the load increases. Not used with DMLC. If not set, the number of consumers stays at concurrentConsumers.

Integer

messageListenerContainerType (consumer (advanced))

The type of the Spring AMQP listener container: DMLC (DirectMessageListenerContainer) calls the route on a thread of the RabbitMQ client, with concurrentConsumers consumers per queue; SMLC (SimpleMessageListenerContainer) calls it on its own consumer threads, each consuming from all the queues, and can add consumers up to maxConcurrentConsumers.

Enum values:

  • DMLC

  • SMLC

DMLC

String

prefetchCount (consumer (advanced))

The prefetch count (basic.qos) of each consumer: how many unacknowledged messages RabbitMQ sends to a consumer at a time. A high value improves throughput; after a reconnect, up to this many messages per consumer may be delivered again. Not used with acknowledgeMode NONE. The default is the prefetchCount of the component, 250.

Integer

retry (consumer (advanced))

A custom StatelessRetryOperationsInterceptor, such as one built with RetryInterceptorBuilder.stateless(), that the listener container uses to retry a message that the route failed to process. When it is set, maximumRetryAttempts, retryDelay and rejectAndDontRequeue are not used.

StatelessRetryOperationsInterceptor

allowNullBody (producer)

Whether to allow sending a message with a null body, which is then sent with an empty body. If false, the default message converter fails to send a null body with a MessageConversionException.

false

boolean

autoDeclareProducer (producer)

Whether the producer declares the exchange, the queues and their bindings, and the dead letter exchange and queue when they are configured, when it starts, as autoDeclare does for the consumer. Without the queues option, it declares a durable queue with a generated name: use skipDeclareQueue and skipBindQueue to declare the exchange only.

false

boolean

confirm (producer)

Whether the producer waits for RabbitMQ to confirm each message sent InOnly (publisher confirms), up to the confirmTimeout: auto waits when the connection factory has publisher confirms (simple or correlated), enabled always waits and needs a connection factory with publisher confirms, and disabled never waits. A message sent InOut is not confirmed.

Enum values:

  • auto

  • enabled

  • disabled

auto

String

confirmTimeout (producer)

The time in milliseconds that the producer waits for RabbitMQ to confirm a message sent InOnly, when it waits for publisher confirms (see confirm). When no confirm arrives in time, the exchange fails with an AmqpTimeoutException; a message that RabbitMQ negatively acknowledges fails too. 0 or a negative value waits forever.

5000

long

replyTimeout (producer)

The time in milliseconds that the producer waits for the reply to a request/reply (InOut) message, which it receives with RabbitMQ direct reply-to. When no reply arrives in time, the exchange fails with an AmqpReplyTimeoutException. 0 or a negative value waits forever: beware that every reply that never arrives then leaks memory.

30000

long

skipBindQueue (producer)

Whether auto-declare (autoDeclare, autoDeclareProducer) skips binding the queues to the exchange.

false

boolean

skipDeclareExchange (producer)

Whether auto-declare (autoDeclare, autoDeclareProducer) skips declaring the exchange and declares only the queues and their bindings, for an exchange that exists already.

false

boolean

skipDeclareQueue (producer)

Whether auto-declare (autoDeclare, autoDeclareProducer) skips declaring the queues, for queues that exist already. They are still bound to the exchange, unless skipBindQueue is true.

false

boolean

usePublisherConnection (producer)

Whether to send the messages on the publisher connection of the connection factory, a separate connection from the one of the consumers, so that a publisher that RabbitMQ blocks does not block the consumers. The consumer sends its replies this way too.

false

boolean

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

args (advanced)

The arguments of the elements that are auto-declared and of the consumers, each with the prefix of its element: arg.exchange., arg.queue. and arg.binding. for the exchange, the queues and their bindings; arg.dlq.exchange., arg.dlq.queue. and arg.dlq.binding. for the dead letter exchange, queue and binding; and arg.consumer. for the consumer arguments of basic.consume. The keys durable and autoDelete of the exchange, and durable, autoDelete and exclusive of a queue, set these flags (durable is true by default, the others false); the other keys are sent as arguments, such as arg.queue.x-message-ttl=60000 for a message TTL of 60 seconds. This is a multi-value option with prefix: arg.

Map

messageConverter (advanced)

A custom Spring AMQP MessageConverter that converts the message body to and from the body of a RabbitMQ message (org.springframework.amqp.core.Message). The default converter turns a received message with a text content type into a String, decoded with its content encoding, and any other message into a byte array; it sends a String as text, converts any other body to a byte array with the type converters, and never serializes or deserializes Java objects.

MessageConverter

messagePropertiesConverter (advanced)

A custom MessagePropertiesConverter of this component that maps the Camel message headers to and from the MessageProperties of a RabbitMQ message (org.springframework.amqp.core.MessageProperties). The default maps the CamelSpringRabbitmq headers to the message properties, and the other headers that the header filter strategy allows to the headers of the RabbitMQ message.

MessagePropertiesConverter

synchronous (advanced)

Whether the consumer processes each exchange synchronously, also when asyncConsumer is enabled. The producer does not use this option.

false

boolean

Message Headers

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

Name Description Default Type

CamelSpringRabbitmqRoutingOverrideKey (producer)

Constant: ROUTING_OVERRIDE_KEY

The routing key to send the message with, instead of the routingKey of the endpoint. The producer removes this header.

String

CamelSpringRabbitmqExchangeOverrideName (producer)

Constant: EXCHANGE_OVERRIDE_NAME

The name of the exchange to send the message to, instead of the exchange of the endpoint (default for the default exchange). The producer removes this header.

String

CamelSpringRabbitmqRedelivered (consumer)

Constant: REDELIVERED

Whether RabbitMQ delivered the message before (the redelivered flag): it was requeued, or delivered to a consumer that did not acknowledge it.

Boolean

CamelSpringRabbitmqDeliveryTag (consumer)

Constant: DELIVERY_TAG

The delivery tag of the message on its channel. With acknowledgeMode MANUAL, the route acknowledges the message with basicAck on the Channel of the CamelSpringRabbitmqChannel exchange property.

long

CamelSpringRabbitmqExchangeName (consumer)

Constant: EXCHANGE_NAME

The exchange name that was used when publishing the message.

String

CamelSpringRabbitmqRoutingKey (consumer)

Constant: ROUTING_KEY

The routing key that was used when publishing the message.

String

CamelSpringRabbitmqDeliveryMode (common)

Constant: DELIVERY_MODE

The delivery mode of the message: PERSISTENT or NON_PERSISTENT. The producer sends a message as PERSISTENT unless this header says otherwise.

Enum values:

  • NON_PERSISTENT

  • PERSISTENT

MessageDeliveryMode

CamelSpringRabbitmqType (common)

Constant: TYPE

Application-specific message type.

String

CamelSpringRabbitmqContentType (common)

Constant: CONTENT_TYPE

The content type of the message. Unless this header is set, the producer sends a String body as text/plain and other bodies as application/octet-stream. The consumer turns the body of a message whose content type starts with text into a String.

String

CamelSpringRabbitmqContentLength (common)

Constant: CONTENT_LENGTH

The length of the message body in bytes, a property of Spring AMQP that RabbitMQ does not carry: the default message converter sets it from the body it sends, and a consumed message does not have it.

long

CamelSpringRabbitmqContentEncoding (common)

Constant: CONTENT_ENCODING

The content encoding of the message, the charset of a text body. The producer encodes a String body with it (with the default charset of the JVM, which it then sets, when the header is not set), and the consumer decodes a text body with it.

String

CamelSpringRabbitmqMessageId (common)

Constant: MESSAGE_ID

Arbitrary message id.

String

CamelSpringRabbitmqCorrelationId (common)

Constant: CORRELATION_ID

Identifier to correlate RPC responses with requests.

String

CamelSpringRabbitmqReplyTo (common)

Constant: REPLY_TO

The reply-to address of the message. A consumer that receives a message with a reply-to sends the result of the route to it as the reply, unless disableReplyTo is enabled.

String

CamelSpringRabbitmqExpiration (common)

Constant: EXPIRATION

The per-message TTL in milliseconds, as a String (the expiration property): RabbitMQ dead-letters or discards the message when it expires in a queue.

String

CamelSpringRabbitmqTimestamp (common)

Constant: TIMESTAMP

Application-provided timestamp.

Date

CamelSpringRabbitmqUserId (common)

Constant: USER_ID

The user id of the message, which RabbitMQ checks against the user of the connection that publishes it.

String

CamelSpringRabbitmqAppId (common)

Constant: APP_ID

The application name.

String

CamelSpringRabbitmqPriority (common)

Constant: PRIORITY

The message priority.

Integer

CamelSpringRabbitmqClusterId (common)

Constant: CLUSTER_ID

The cluster id.

String

Message Body

The message body at each side of the Spring RabbitMQ component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

text or bytes

A String when the content type starts with text, as for text this component sends; a byte array otherwise, JSON and Java serialized objects too, which are not deserialized.

Not known when messageConverter is set.

Consumer reply

text, bytes, stream or file

The reply to a message with a reply-to, converted as the producer converts a body: a Map or a POJO fails.

  • With allowNullBody=true: null, text, bytes, stream or file

Not known when messageConverter is set.

Producer input

text, bytes, stream or file

Text, bytes, a stream or a file, sent as a byte array, text as text/plain unless the CamelSpringRabbitmqContentType header says another type. A Map or a POJO fails, as it is not serialized: marshal it first.

  • With allowNullBody=true: null, text, bytes, stream or file

Not known when messageConverter is set.

Producer output

unknown

Unchanged for a message that expects no reply (InOnly). A message that expects one (InOut) gets the body of the reply as the consumer gives it: a String for a text content type, a byte array otherwise.

  • With exchangePattern=InOnly: unchanged

  • With disableReplyTo=true: unchanged

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

Using a connection factory

To connect to RabbitMQ, you need to set up a ConnectionFactory (same as with JMS) with the login details such as:

It is recommended to use CachingConnectionFactory from spring-rabbit as it comes with connection pooling out of the box.
<bean id="rabbitConnectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
  <property name="uri" value="amqp://localhost:5672"/>
</bean>

The ConnectionFactory is auto-detected by default, so you can do:

  • Java

  • XML

  • YAML

from("direct:cheese")
    .to("spring-rabbitmq:foo?routingKey=cheese");
<camelContext>
  <route>
    <from uri="direct:cheese"/>
    <to uri="spring-rabbitmq:foo?routingKey=cheese"/>
  </route>
</camelContext>
- route:
    from:
      uri: direct:cheese
      steps:
        - to:
            uri: spring-rabbitmq:foo
            parameters:
              routingKey: cheese

Noticing a dead or silent broker

How soon a route notices a broker that stopped answering without closing the connection (the host is gone, or a firewall or NAT drops the packets) depends on the connection factory. The durations below describe how Spring AMQP and the RabbitMQ Java client behave by default, approximately; they are not guarantees of Camel.

Publisher confirms. Without publisher confirms, the producer hands the message to the client and reports success: on a silent or reset connection the send succeeds and the message can be lost without an error. Configure the connection factory with simple publisher confirms. With the default confirm=auto the producer then waits up to confirmTimeout (5 seconds) for RabbitMQ to confirm each message sent InOnly, and the send fails when it is not confirmed, so the error handler can redeliver it. confirm=enabled waits the same way, and needs the connection factory to have publisher confirms.

Heartbeat. The RabbitMQ Java client notices a silent connection through the heartbeat, 60 seconds by default (the lower of the values that the client and the broker request). It reads with a timeout of a quarter of the heartbeat and closes the connection after more than 8 such timeouts in a row: about 2.25 × the heartbeat, so about 135 seconds by default. Until then a consumer receives nothing and logs no error. A lower heartbeat notices it sooner, for example about 34 seconds with 15 seconds.

Channel operations. An operation that waits for an answer of the broker on a channel, such as opening a channel or cancelling a consumer when the route stops, waits until the connection is closed or for up to the channelRpcTimeout of the client, 10 minutes by default.

<bean id="rabbitConnectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
  <property name="uri" value="amqp://localhost:5672"/>
  <property name="publisherConfirmType" value="SIMPLE"/>
  <property name="requestedHeartBeat" value="15"/>
</bean>

In Java, connectionFactory.getRabbitConnectionFactory().setChannelRpcTimeout(30000) sets the channel timeout. With Spring Boot:

spring.rabbitmq.publisher-confirm-type=simple
spring.rabbitmq.requested-heartbeat=15s
spring.rabbitmq.channel-rpc-timeout=30s

After the connection breaks, the broker requeues the messages that the consumer received but did not acknowledge, while the consumer may still process the ones it had already received: expect duplicates after a reconnect, up to prefetchCount (250 by default) per consumer. Make the processing idempotent, or lower prefetchCount.

Suspending or stopping a route. The consumer stops its listener container, which cancels its consumers and waits for the broker to answer, then waits up to its shutdownTimeout (the shutdownTimeout of the component, 5 seconds by default, unless a custom listenerContainerFactory sets another one) for the messages that the route is still processing. A route that suspends its own consumer, such as with a route policy when an exchange is done, waits that whole shutdownTimeout, as the listener container waits for the message that the route is processing; the listener container then closes the channel of that message, so the broker delivers it again once the route is resumed (unless it was acknowledged on delivery, with acknowledgeMode=NONE). The consumer waits for the listener container to stop at most the shutdownTimeout of the component plus the shutdownAwaitTermination of the ExecutorServiceManager (10 seconds by default), so that a broker that does not answer the cancel does not hold up the graceful shutdown. When that time elapses, the consumer logs a WARN with the endpoint and its queues, and returns: the listener container goes on stopping in the background, and is destroyed once the cancel returns. When the route is resumed or started again, the consumer creates a new listener container.

Default Exchange Name

To use default exchange name (which would be an empty exchange name in RabbitMQ) then you should use default as name in the endpoint uri, such as:

  • Java

  • XML

  • YAML

to("spring-rabbitmq:default?routingKey=foo")
<to uri="spring-rabbitmq:default?routingKey=foo"/>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: spring-rabbitmq:default
            parameters:
              routingKey: foo

Auto declare exchanges, queues and bindings

Before you can send or receive messages from RabbitMQ, then exchanges, queues and bindings must be setup first.

Since Camel 4.5, a consumer declares them when it starts, as autoDeclare is true by default: the exchange, of the exchangeType (direct by default), the queues, and the binding between the exchange, the queues and the routing key. A producer declares them only with autoDeclareProducer=true.

If the broker already has one of these elements with other settings, such as an exchange of another type or a queue with other arguments, the broker refuses the declaration with PRECONDITION_FAILED and the consumer fails to start. Configure the endpoint with the settings of the existing elements, or turn the declaration off with autoDeclare=false (on the endpoint or the component), or for some elements with skipDeclareExchange, skipDeclareQueue or skipBindQueue.

The consumer declares them again each time the connection factory opens a new connection, for example after the connection to RabbitMQ was lost: a queue that RabbitMQ deleted meanwhile, such as an auto-delete or exclusive queue, is declared again when the consumer reconnects.

When RabbitMQ is not available when the consumer starts, the consumer logs a warning and starts anyway: the listener container keeps trying to connect, and the exchange, queue and binding are declared when it connects. To fail the start instead, set testConnectionOnStartup=true.

With a CachingConnectionFactory whose cache mode is CONNECTION, the consumer declares only when it starts, as Spring’s RabbitAdmin, and fails to start when RabbitMQ is not available.

The elements can be configured using the multivalued args option.

For example, to specify the queue as exclusive, you can configure the endpoint uri with arg.queue.exclusive=true.

Exchanges

Option Type Description Default

autoDelete

boolean

True if the server should delete the exchange when it is no longer in use (if all bindings are deleted).

false

durable

boolean

A durable exchange will survive a server restart.

true

You can also configure any additional x- arguments. See details in the RabbitMQ documentation.

Queues

Option Type Description Default

autoDelete

boolean

True if the server should delete the queue when it is no longer in use (queue that has had at least one consumer is deleted when last consumer unsubscribes).

false

durable

boolean

A durable queue will survive a server restart.

true

exclusive

boolean

Whether the queue is exclusive

false

x-dead-letter-exchange

String

The name of the dead letter exchange. The deadLetterExchange option takes precedence when it is set.

x-dead-letter-routing-key

String

The routing key for the dead letter exchange. The deadLetterRoutingKey option takes precedence when it is set together with deadLetterExchange.

You can also configure any additional x- arguments, such as the message time to live, via x-message-ttl, and many others. See details in the RabbitMQ documentation.

Mapping from Camel to RabbitMQ

The message body is mapped from Camel Message body to a byte[] which is the type that RabbitMQ uses for message body. Camel will use its type converter to convert the message body to a byte array.

Spring Rabbit comes out of the box with support for mapping Java serialized objects, but Camel Spring RabbitMQ does not support this due to security vulnerabilities and using Java objects is a bad design as it enforces strong coupling.

Custom message headers are mapped from Camel Message headers to RabbitMQ headers. This behaviour can be customized by configuring a new implementation of HeaderFilterStrategy on the Camel component.

The content type of a sent message is taken from the CamelSpringRabbitmqContentType header when it is set, otherwise it is derived from the message body (text/plain for a String, application/octet-stream for other bodies). The consumer sets this header to the content type of the consumed message, so a route that forwards a consumed message to another queue keeps that content type. When the route changes the type of the body, such as turning a text message into a byte array, remove the header before sending, otherwise the receiver reads the body with the content type of the original message (a byte array sent as text/plain is received as a String):

  • Java

  • XML

  • YAML

from("spring-rabbitmq:orders?queues=incoming")
    .convertBodyTo(byte[].class)
    .removeHeader("CamelSpringRabbitmqContentType")
    .to("spring-rabbitmq:orders?routingKey=binary");
<route>
  <from uri="spring-rabbitmq:orders?queues=incoming"/>
  <convertBodyTo type="byte[]"/>
  <removeHeader name="CamelSpringRabbitmqContentType"/>
  <to uri="spring-rabbitmq:orders?routingKey=binary"/>
</route>
- route:
    from:
      uri: spring-rabbitmq:orders
      parameters:
        queues: incoming
      steps:
        - convertBodyTo:
            type: "byte[]"
        - removeHeader:
            name: CamelSpringRabbitmqContentType
        - to:
            uri: spring-rabbitmq:orders
            parameters:
              routingKey: binary

Request / Reply

Request and reply messaging is supported using RabbitMQ direct reply-to.

The example below will do request/reply, where the message is sent via the cheese exchange name and routing key foo.bar, which is being consumed by the second Camel route, that prepends the message with `Hello `, and then sends back the message.

So if we send World as message body to direct:start then, we will se the message being logged

  • log:request → World

  • log:input → World

  • log:response → Hello World

Java-only: Java DSL with ExchangePattern.InOut and body().prepend()
from("direct:start")
    .to("log:request")
    .to(ExchangePattern.InOut, "spring-rabbitmq:cheese?routingKey=foo.bar")
    .to("log:response");

from("spring-rabbitmq:cheese?queues=myqueue&routingKey=foo.bar")
    .to("log:input")
    .transform(body().prepend("Hello "));

The consumer sets the CamelSpringRabbitmqContentType header to the content type of the request. When the route leaves this header unchanged, the reply inherits the content type of the request depending on the reply body:

  • A String reply keeps it, so a JSON String reply to an application/json request is sent as application/json.

  • A byte array or stream reply (such as the output of marshal) keeps it, unless it is a text content type such as text/plain. Then the reply is sent as application/octet-stream, so a byte array reply to a text request is received as a byte array.

  • Any other reply body does not keep it, and the message converter derives the content type from the reply body.

A content type the route sets in the CamelSpringRabbitmqContentType header, other than the one of the request, is always used.

When the route ends with a Spring AMQP org.springframework.amqp.core.Message as the body, that message is sent as the reply as it is. If it has no correlation id, the correlation id of the request is set on it, so the requester can match the reply.

Reuse endpoint and send to different destinations computed at runtime

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

Using toD is easier than specifying the dynamic destination with headers

You can specify using the following headers:

Header Type Description

CamelSpringRabbitmqExchangeOverrideName

String

The exchange name.

CamelSpringRabbitmqRoutingOverrideKey

String

The routing key.

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

  • Java

  • XML

  • YAML

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

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

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

Java-only: Java handler method
public void setExchangeHeader(Exchange exchange) {
   String region = ....
   exchange.getIn().setHeader("CamelSpringRabbitmqExchangeOverrideName", "order-" + region);
}

Then Camel will read this header and use it as the exchange name instead of the one configured on the endpoint. So, in this example Camel sends the message to spring-rabbitmq:order-emea, assuming the region value was emea.

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

Using toD

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

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

  • Java

  • XML

  • YAML

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

Manual Acknowledgement

If we need to manually acknowledge a message for some use case, we can do it by setting and acknowledgeMode to Manual and using the below snippet of code to get Channel and deliveryTag to manually acknowledge the message:

Java-only: inline Processor with Spring RabbitMQ API
from("spring-rabbitmq:%s?queues=%s&acknowledgeMode=MANUAL")
    .process(exchange -> {
        Channel channel = exchange.getProperty(SpringRabbitMQConstants.CHANNEL, Channel.class);
        long deliveryTag = exchange.getMessage().getHeader(SpringRabbitMQConstants.DELIVERY_TAG, long.class);
        channel.basicAck(deliveryTag, false);
    })