Camel Components

Nats

Since Camel 2.17

Both producer and consumer are supported

NATS is a fast and reliable messaging platform.

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

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

URI format

nats:topic[?options]

Where topic is the topic name

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 Nats component supports the following options which are listed below.

Name Description Default Type

configuration (common)

To use a shared configuration.

NatsConfiguration

connectionTimeout (common)

The time in milliseconds to wait for a connection to a server to be established.

2000

int

flushConnection (common)

Whether to flush the connection, waiting until the server has received what was sent, when the consumer or the producer stops.

true

boolean

flushTimeout (common)

The time in milliseconds to wait for the flush of the connection when stopping.

1000

int

jetstreamEnabled (common)

Whether to use JetStream: the producer publishes to a stream and waits for its acknowledgement, and the consumer reads from the stream named by jetstreamName. When the server does not have JetStream, the endpoint uses core NATS.

false

boolean

jetstreamName (common)

The name of the JetStream stream. The consumer reads from this stream (it is required for a JetStream consumer). When the stream does not exist, the consumer creates it with the subject of the topic. The producer creates it in the same way, unless another stream already takes in the subject. The producer publishes to the subject, and the message is stored by the stream that takes in the subject, whatever its name.

String

maxPingsOut (common)

The maximum number of pings without a response from the server. When it is reached, the client considers the connection stale.

2

int

maxReconnectAttempts (common)

The maximum number of reconnect attempts to each server, when reconnect is enabled. -1 means no limit, and 0 means no reconnect.

60

int

noEcho (common)

Whether to ask the server not to send back to this connection the messages it publishes, when the connection also subscribes to their subject.

false

boolean

noRandomizeServers (common)

Whether to connect to the servers in the order they are given, instead of in a random order.

false

boolean

pedantic (common)

Whether to ask the server for pedantic mode, in which it does extra checks on what the client sends. This affects performance.

false

boolean

pingInterval (common)

The interval in milliseconds at which the client sends a ping to the server, to check that the connection is still alive.

120000

int

reconnect (common)

Whether the NATS client reconnects when the connection to the server is lost. When disabled, the connection is closed instead.

true

boolean

reconnectTimeWait (common)

The time in milliseconds to wait between two reconnect attempts to the same server.

2000

int

requestCleanupInterval (common)

The interval in milliseconds at which the NATS client removes the requests that were cancelled or timed out. The client gives up on a request without a timeout of its own, such as a request-reply message of the producer or an asynchronous JetStream publish, after this interval (to twice that).

5000

int

servers (common)

The URLs of one or more NATS servers, separated by comma. A URL without a scheme, such as localhost:4222, gets nats:// in front of it. Not used when a connection is given.

String

verbose (common)

Whether to ask the server for verbose mode, in which it confirms each protocol message with +OK.

false

boolean

ackPolicy (consumer)

The acknowledgement policy of the JetStream consumer. None: the server does not wait for an acknowledgement, so a message that failed in Camel is not delivered again. All: the acknowledgement of a message also acknowledges all the messages before it. Explicit: each message is acknowledged on its own, after Camel processed it, and a message that failed is negatively acknowledged (nak), so the server delivers it again. Not used when consumerConfiguration is set.

Enum values:

  • None

  • All

  • Explicit

Explicit

AckPolicy

ackWait (consumer)

The time in milliseconds that the server waits for the acknowledgement of a JetStream message before it delivers the message again. 0 or less uses the server default (30 seconds). Not used when consumerConfiguration is set.

30000

long

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

durableName (consumer)

The name of the durable JetStream consumer, which keeps its position in the stream when Camel stops. The consumer on the server is named after this value followed by -durable (orders becomes orders-durable). Without it, the consumer is ephemeral. It cannot contain whitespace, '.', '*', '>', path separators (forward or backward slash) or non-printable characters. Not used when consumerConfiguration is set.

String

manualAck (consumer)

Whether the route acknowledges the JetStream messages itself, with the NatsManualAck that the consumer puts in the CamelNatsManualAck header (ack, nak and term). The consumer then does not acknowledge a message when its exchange completes: a message that is not acknowledged is delivered again after ackWait. Only used with jetstreamEnabled=true, and has no effect with ackPolicy=None.

false

boolean

maxDeliver (consumer)

The maximum number of times the server delivers a JetStream message to the consumer. After that, the server no longer delivers the message, which stays in the stream. 0 (the default) keeps the server default, which is no limit. Set it so that a message that always fails is not delivered forever. Not used when consumerConfiguration is set.

long

maxMessages (consumer)

The number of messages after which the consumer unsubscribes from the topic, and receives no more messages. Not used with JetStream.

String

nackWait (consumer)

The delay in milliseconds before the server delivers a JetStream message again, after the consumer negatively acknowledged (nak) it because its exchange failed. 0 or less delivers it again at once, which can make the consumer process the same message over and over again while an error lasts.

5000

long

poolSize (consumer)

The size of the thread pool of the consumer. The pool runs the subscribe and, with a JetStream pull subscription, the fetch loop. The messages are processed one at a time, on the thread of the NATS dispatcher or of the fetch loop, so a larger pool does not process them in parallel.

10

int

pullBatchSize (consumer)

The maximum number of messages to fetch per pull request. Only used with a JetStream pull subscription.

10

int

pullFetchTimeout (consumer)

The maximum time in milliseconds that a fetch waits for messages. Only used with a JetStream pull subscription.

1000

long

pullSubscription (consumer)

Whether the JetStream consumer uses a pull subscription, in which it fetches the messages in batches, or a push subscription, in which the server delivers them.

true

boolean

queueName (consumer)

The name of the queue group to subscribe with. The server delivers each message to only one of the subscribers of the group. With JetStream, it is the deliver group of a push subscription; a pull subscription does not use it.

String

replyToDisabled (consumer)

Whether the consumer does not send a reply to a message that has a reply subject, even with exchangePattern=InOut.

false

boolean

consumerConfiguration (consumer (advanced))

A JetStream ConsumerConfiguration to use for the consumer, for settings that have no option of their own. When set, it is used as it is, and the options ackPolicy, ackWait, maxDeliver and durableName are not used.

ConsumerConfiguration

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

replySubject (producer)

The reply subject to set on the messages that the producer publishes without waiting for a reply (exchangePattern=InOnly), so that the subscribers can send their responses there. Not used for request-reply (InOut), where the NATS client uses its own reply subject.

String

requestTimeout (producer)

The time in milliseconds that the producer waits for the reply of a request-reply message (exchangePattern=InOut) and, with JetStream, for the acknowledgement of a published message. The NATS client also gives up on a reply, and with jetstreamAsync=true on the acknowledgement, after requestCleanupInterval (to twice that), so a longer wait needs a longer requestCleanupInterval too.

20000

long

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

connection (advanced)

An existing NATS Connection to use, instead of the connection that Camel creates from the servers and the connection options. Camel does not close it.

Connection

headerFilterStrategy (advanced)

To use a custom HeaderFilterStrategy to filter the headers that are sent to and received from NATS.

HeaderFilterStrategy

jetstreamAsync (advanced)

Whether the producer publishes to JetStream with the asynchronous publish of the NATS client, waiting up to requestTimeout for the acknowledgement, or with the synchronous one. Either way, the exchange completes once the stream acknowledged the message.

true

boolean

traceConnection (advanced)

Whether the NATS client prints connection trace messages to standard out, for debugging connection issues.

false

boolean

credentialsFilePath (security)

The path of a NATS credentials file, used to authenticate with the server. It is loaded from the classpath by default; prefix it with classpath:, file: or http: to load it from elsewhere.

String

hostnameVerification (security)

Whether to check that the certificate of the NATS server matches the host Camel connects to, when TLS is used. The client then keeps the host name of a server for TLS, and connects to the fastest of its IP addresses. A server that is given, or that the cluster announces, by its IP address needs a certificate that names that address. When disabled, any certificate trusted by the JVM, or by the sslContextParameters, is accepted, whatever host it was issued for.

true

boolean

secure (security)

Whether TLS is required for the connection.

false

boolean

sslContextParameters (security)

To configure security using SSLContextParameters.

SSLContextParameters

useGlobalSslContextParameters (security)

Enable usage of global SSL context parameters.

false

boolean

Endpoint Options

The Nats endpoint is configured using URI syntax:

nats:topic

With the following path and query parameters:

Path Parameters

Name Description Default Type

topic (common)

Required The NATS subject that the producer publishes to, or that the consumer subscribes to. The consumer accepts the wildcards * (one token) and > (one or more tokens at the end).

String

Query Parameters

Name Description Default Type

connectionTimeout (common)

The time in milliseconds to wait for a connection to a server to be established.

2000

int

flushConnection (common)

Whether to flush the connection, waiting until the server has received what was sent, when the consumer or the producer stops.

true

boolean

flushTimeout (common)

The time in milliseconds to wait for the flush of the connection when stopping.

1000

int

jetstreamEnabled (common)

Whether to use JetStream: the producer publishes to a stream and waits for its acknowledgement, and the consumer reads from the stream named by jetstreamName. When the server does not have JetStream, the endpoint uses core NATS.

false

boolean

jetstreamName (common)

The name of the JetStream stream. The consumer reads from this stream (it is required for a JetStream consumer). When the stream does not exist, the consumer creates it with the subject of the topic. The producer creates it in the same way, unless another stream already takes in the subject. The producer publishes to the subject, and the message is stored by the stream that takes in the subject, whatever its name.

String

maxPingsOut (common)

The maximum number of pings without a response from the server. When it is reached, the client considers the connection stale.

2

int

maxReconnectAttempts (common)

The maximum number of reconnect attempts to each server, when reconnect is enabled. -1 means no limit, and 0 means no reconnect.

60

int

noEcho (common)

Whether to ask the server not to send back to this connection the messages it publishes, when the connection also subscribes to their subject.

false

boolean

noRandomizeServers (common)

Whether to connect to the servers in the order they are given, instead of in a random order.

false

boolean

pedantic (common)

Whether to ask the server for pedantic mode, in which it does extra checks on what the client sends. This affects performance.

false

boolean

pingInterval (common)

The interval in milliseconds at which the client sends a ping to the server, to check that the connection is still alive.

120000

int

reconnect (common)

Whether the NATS client reconnects when the connection to the server is lost. When disabled, the connection is closed instead.

true

boolean

reconnectTimeWait (common)

The time in milliseconds to wait between two reconnect attempts to the same server.

2000

int

requestCleanupInterval (common)

The interval in milliseconds at which the NATS client removes the requests that were cancelled or timed out. The client gives up on a request without a timeout of its own, such as a request-reply message of the producer or an asynchronous JetStream publish, after this interval (to twice that).

5000

int

servers (common)

The URLs of one or more NATS servers, separated by comma. A URL without a scheme, such as localhost:4222, gets nats:// in front of it. Not used when a connection is given.

String

verbose (common)

Whether to ask the server for verbose mode, in which it confirms each protocol message with +OK.

false

boolean

ackPolicy (consumer)

The acknowledgement policy of the JetStream consumer. None: the server does not wait for an acknowledgement, so a message that failed in Camel is not delivered again. All: the acknowledgement of a message also acknowledges all the messages before it. Explicit: each message is acknowledged on its own, after Camel processed it, and a message that failed is negatively acknowledged (nak), so the server delivers it again. Not used when consumerConfiguration is set.

Enum values:

  • None

  • All

  • Explicit

Explicit

AckPolicy

ackWait (consumer)

The time in milliseconds that the server waits for the acknowledgement of a JetStream message before it delivers the message again. 0 or less uses the server default (30 seconds). Not used when consumerConfiguration is set.

30000

long

durableName (consumer)

The name of the durable JetStream consumer, which keeps its position in the stream when Camel stops. The consumer on the server is named after this value followed by -durable (orders becomes orders-durable). Without it, the consumer is ephemeral. It cannot contain whitespace, '.', '*', '>', path separators (forward or backward slash) or non-printable characters. Not used when consumerConfiguration is set.

String

manualAck (consumer)

Whether the route acknowledges the JetStream messages itself, with the NatsManualAck that the consumer puts in the CamelNatsManualAck header (ack, nak and term). The consumer then does not acknowledge a message when its exchange completes: a message that is not acknowledged is delivered again after ackWait. Only used with jetstreamEnabled=true, and has no effect with ackPolicy=None.

false

boolean

maxDeliver (consumer)

The maximum number of times the server delivers a JetStream message to the consumer. After that, the server no longer delivers the message, which stays in the stream. 0 (the default) keeps the server default, which is no limit. Set it so that a message that always fails is not delivered forever. Not used when consumerConfiguration is set.

long

maxMessages (consumer)

The number of messages after which the consumer unsubscribes from the topic, and receives no more messages. Not used with JetStream.

String

nackWait (consumer)

The delay in milliseconds before the server delivers a JetStream message again, after the consumer negatively acknowledged (nak) it because its exchange failed. 0 or less delivers it again at once, which can make the consumer process the same message over and over again while an error lasts.

5000

long

poolSize (consumer)

The size of the thread pool of the consumer. The pool runs the subscribe and, with a JetStream pull subscription, the fetch loop. The messages are processed one at a time, on the thread of the NATS dispatcher or of the fetch loop, so a larger pool does not process them in parallel.

10

int

pullBatchSize (consumer)

The maximum number of messages to fetch per pull request. Only used with a JetStream pull subscription.

10

int

pullFetchTimeout (consumer)

The maximum time in milliseconds that a fetch waits for messages. Only used with a JetStream pull subscription.

1000

long

pullSubscription (consumer)

Whether the JetStream consumer uses a pull subscription, in which it fetches the messages in batches, or a push subscription, in which the server delivers them.

true

boolean

queueName (consumer)

The name of the queue group to subscribe with. The server delivers each message to only one of the subscribers of the group. With JetStream, it is the deliver group of a push subscription; a pull subscription does not use it.

String

replyToDisabled (consumer)

Whether the consumer does not send a reply to a message that has a reply subject, even with exchangePattern=InOut.

false

boolean

bridgeErrorHandler (consumer (advanced))

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

false

boolean

consumerConfiguration (consumer (advanced))

A JetStream ConsumerConfiguration to use for the consumer, for settings that have no option of their own. When set, it is used as it is, and the options ackPolicy, ackWait, maxDeliver and durableName are not used.

ConsumerConfiguration

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

replySubject (producer)

The reply subject to set on the messages that the producer publishes without waiting for a reply (exchangePattern=InOnly), so that the subscribers can send their responses there. Not used for request-reply (InOut), where the NATS client uses its own reply subject.

String

requestTimeout (producer)

The time in milliseconds that the producer waits for the reply of a request-reply message (exchangePattern=InOut) and, with JetStream, for the acknowledgement of a published message. The NATS client also gives up on a reply, and with jetstreamAsync=true on the acknowledgement, after requestCleanupInterval (to twice that), so a longer wait needs a longer requestCleanupInterval too.

20000

long

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

connection (advanced)

An existing NATS Connection to use, instead of the connection that Camel creates from the servers and the connection options. Camel does not close it.

Connection

headerFilterStrategy (advanced)

To use a custom HeaderFilterStrategy to filter the headers that are sent to and received from NATS.

HeaderFilterStrategy

jetstreamAsync (advanced)

Whether the producer publishes to JetStream with the asynchronous publish of the NATS client, waiting up to requestTimeout for the acknowledgement, or with the synchronous one. Either way, the exchange completes once the stream acknowledged the message.

true

boolean

traceConnection (advanced)

Whether the NATS client prints connection trace messages to standard out, for debugging connection issues.

false

boolean

credentialsFilePath (security)

The path of a NATS credentials file, used to authenticate with the server. It is loaded from the classpath by default; prefix it with classpath:, file: or http: to load it from elsewhere.

String

hostnameVerification (security)

Whether to check that the certificate of the NATS server matches the host Camel connects to, when TLS is used. The client then keeps the host name of a server for TLS, and connects to the fastest of its IP addresses. A server that is given, or that the cluster announces, by its IP address needs a certificate that names that address. When disabled, any certificate trusted by the JVM, or by the sslContextParameters, is accepted, whatever host it was issued for.

true

boolean

secure (security)

Whether TLS is required for the connection.

false

boolean

sslContextParameters (security)

To configure security using SSLContextParameters.

SSLContextParameters

Message Headers

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

Name Description Default Type

CamelNatsMessageTimestamp (common)

Constant: NATS_MESSAGE_TIMESTAMP

The time, in milliseconds since the epoch, at which Camel received the message (not the time it was published).

long

CamelNatsSID (common)

Constant: NATS_SID

The ID (SID) of the subscription that received the message.

String

CamelNatsReplyTo (common)

Constant: NATS_REPLY_TO

The reply subject of the message, or null when it has none.

String

CamelNatsSubject (common)

Constant: NATS_SUBJECT

The subject of the message.

String

CamelNatsQueueName (common)

Constant: NATS_QUEUE_NAME

The queue group of the subscription that received the message, or null when it has none.

String

CamelNatsStatusCode (consumer)

Constant: NATS_STATUS_CODE

The code of a NATS status message. Only set for a status message.

int

CamelNatsStatusError (consumer)

Constant: NATS_STATUS_ERROR

The text of a NATS status message. Only set for a status message.

String

CamelNatsDeliveryCounter (consumer)

Constant: NATS_DELIVERY_COUNTER

The number of times the message has been delivered: 1 for the first delivery, more than 1 when the server delivered it again. Always 1 for a core NATS message.

long

CamelNatsManualAck (consumer)

Constant: NATS_MANUAL_ACK

The NatsManualAck to acknowledge the JetStream message with. Only set with manualAck=true and jetstreamEnabled=true.

NatsManualAck

Message Body

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

bytes (byte[])

The payload of the NATS message as a byte array, empty for a message without one: convert or unmarshal it.

Consumer reply

any

Only with exchangePattern=InOut is a core NATS message with a reply subject answered, with the body the route ends with: text, bytes, a stream or a file, and no body sends an empty reply. A Map or a POJO sends no reply, and the requester times out.

  • With exchangePattern=InOut: null, text, bytes, stream or file

Producer input

text, bytes, stream or file

What converts to a byte array: text, bytes, a stream or a file. A Map or a POJO is sent as its toString(), and a List or no body fails: marshal it first.

Producer output

unknown

Unchanged for a message that expects no reply (InOnly). A message that expects one (InOut) waits for the reply, up to requestTimeout, and gets its payload as a byte array.

  • With exchangePattern=InOnly: unchanged

  • With exchangePattern=InOut: bytes (byte[])

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

Deterministic simulation tests

The consumer of the Nats component is tested with deterministic simulation tests: the real consumer runs under a seeded virtual-time scheduler against a fake of the external system, which injects faults while the tests check invariants. A failing seed can be replayed. These are the fake worlds of the component:

World What it checks Issues

NatsWorld

Fake: FakeJetStream: a server with one JetStream stream and its pull consumers (AckWait, MaxDeliver, Nak), behind a jnats Connection given with the connection option

Tests: NatsConsumerDstTest

Covers:

  • the JetStream pull consumer with explicit acks and naks, ephemeral or durable

  • AckWait and MaxDeliver

  • route stop and start, also while the consumer waits in a fetch

  • a server restart that deletes the ephemeral consumer, and the subscription made again

Faults:

  • a fetch ends empty while the connection is down

  • the flush of the stop times out

  • an ack is lost

  • the server restarts (409 Server Shutdown) or the consumer is deleted (409 Consumer Deleted)

  • processing fails

  • processing is slower than AckWait

Invariants:

  • the consumer uses the connection as documented

  • a message is acknowledged only after its exchange completed

  • a message is nak’d only after its exchange failed

  • a stopped consumer leaves no subscription active

  • every message is acknowledged once the faults cleared, or given up after MaxDeliver (or skipped by a consumer made again after its ack was lost)

The worlds and their tests are in the test sources of the component. How to run them, replay a seed and write a world is described in Running the tests and Writing a fake world.

Usage

Configuring servers

You configure the NATS servers on either the component or the endpoint.

For example, to configure this once on the component, you can do:

Java-only: configuring NATS servers on the component
NatsComponent nats = context.getComponent("nats", NatsComponent.class);
nats.setServers("someserver:4222,someotherserver:42222");

Notice how you can specify multiple servers separated by comma.

Or you can specify the servers in the endpoint URI

  • Java

  • XML

  • YAML

from("direct:send").to("nats:test?servers=localhost:4222");
<route>
  <from uri="direct:send"/>
  <to uri="nats:test?servers=localhost:4222"/>
</route>
- route:
    from:
      uri: direct:send
      steps:
        - to:
            uri: nats:test
            parameters:
              servers: localhost:4222

The endpoint configuration will override any server configuration on the component level.

Configuring username and password or token

You can specify username and password for the servers in the server URLs, where its username:password@url, or token@url etc:

Java-only: configuring NATS servers with credentials
NatsComponent nats = context.getComponent("nats", NatsComponent.class);
nats.setServers("scott:tiger@someserver:4222,superman:123@someotherserver:42222");

If you are using Camel Main or Spring Boot, you can configure the server urls in the application.properties file

camel.component.nats.servers=scott:tiger@someserver:4222,superman:123@someotherserver:42222

Request/Reply support

The producer supports request/reply: when the exchange pattern is InOut, it waits for the reply message, up to requestTimeout, and the payload of the reply becomes the message body, as a byte array. The NATS client also gives up on the reply after requestCleanupInterval (5 seconds by default) to twice that, so set both to wait longer.

The consumer sends back the message body as the reply message, when routing the message is complete, if the message has a reply subject and the consumer has exchangePattern=InOut. The body must convert to a byte array: text, bytes, a stream or a file. A body that does not, such as a Map, sends no reply.

A consumer replies when its exchangePattern is InOut, the message has a reply subject, replyToDisabled is false, and the exchange did not fail (NATS has no error reply, so a failed exchange is not answered and the requester times out). The body the route ends with is converted to a byte array and published to the reply subject:

  • A route that ends with no body sends an empty reply (0 bytes), so the requester gets an answer.

  • A body that does not convert to a byte array, such as a Map or a POJO, is not sent. No reply is published, and the error goes to the exception handler of the consumer, which logs it at WARN level by default. Convert the body in the route, for example to JSON or a String, before the route ends.

Replies are for core NATS only. The reply subject of a JetStream message is its ack subject, so a consumer with jetstreamEnabled=true never replies to a JetStream message, even when exchangePattern is InOut. The consumer logs a WARN when it starts with this combination.

Examples

Producer example

  • Java

  • XML

  • YAML

from("direct:send")
  .to("nats:mytopic");
<route>
  <from uri="direct:send"/>
  <to uri="nats:mytopic"/>
</route>
- route:
    from:
      uri: direct:send
      steps:
        - to:
            uri: nats:mytopic

In case of using authorization, you can directly specify your credentials in the server URL

  • Java

  • XML

  • YAML

from("direct:send")
  .to("nats:mytopic?servers=username:password@localhost:4222");
<route>
  <from uri="direct:send"/>
  <to uri="nats:mytopic?servers=username:password@localhost:4222"/>
</route>
- route:
    from:
      uri: direct:send
      steps:
        - to:
            uri: nats:mytopic
            parameters:
              servers: "username:password@localhost:4222"

or your token

  • Java

  • XML

  • YAML

from("direct:send")
  .to("nats:mytopic?servers=token@localhost:4222");
<route>
  <from uri="direct:send"/>
  <to uri="nats:mytopic?servers=token@localhost:4222"/>
</route>
- route:
    from:
      uri: direct:send
      steps:
        - to:
            uri: nats:mytopic
            parameters:
              servers: "token@localhost:4222"

Consumer example

  • Java

  • XML

  • YAML

from("nats:mytopic?maxMessages=5&queueName=myqueue")
  .to("mock:result");
<route>
  <from uri="nats:mytopic?maxMessages=5&amp;queueName=myqueue"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: nats:mytopic
      parameters:
        maxMessages: 5
        queueName: myqueue
      steps:
        - to:
            uri: mock:result

JetStream producer

With jetstreamEnabled=true, the producer publishes each message to JetStream and waits until the stream that takes in the subject has stored it. Sending fails with 503 No Responders Available For Request when no stream takes in the subject. On a server without JetStream, the message is published as plain NATS.

When jetstreamName is set, the producer checks at startup that this stream exists. When it does not, and no other stream takes in the subject, the producer creates it with the subject of the topic, as the consumer does. When the stream cannot be checked or created, the producer logs a WARN and starts anyway. The message is stored by the stream that takes in the subject, whatever its name.

requestTimeout is how long the producer waits for the acknowledgement. With jetstreamAsync=true (the default), the NATS client also gives up on the acknowledgement after requestCleanupInterval (5 seconds by default) to twice that, so set both to wait longer.

Manual Acknowledgment (JetStream)

When consuming from JetStream, by default messages are automatically acknowledged after successful route processing, or negatively acknowledged (redelivered) on failure.

To take full control of acknowledgment, set manualAck=true on the consumer endpoint. This disables automatic acknowledgment and exposes a NatsManualAck object as the CamelNatsManualAck message header.

Java-only: manual acknowledgment with NatsManualAck in a processor
from("nats:mytopic?jetstreamEnabled=true&jetstreamName=mystream&durableName=myconsumer&pullSubscription=false&manualAck=true")
    .process(exchange -> {
        // do work ...

        NatsManualAck manualAck = exchange.getIn().getHeader("CamelNatsManualAck", NatsManualAck.class);
        manualAck.ack();
    });

If the route completes without calling any NatsManualAck method, the message remains unacknowledged and NATS will redeliver it after ackWait expires (default 30 seconds).

JetStream push consumer whose consumer was deleted

With jetstreamEnabled=true and pullSubscription=false, the server deletes an ephemeral JetStream consumer (no durableName, and no durable name in the consumerConfiguration) after about 5 seconds without a subscriber, for example while the client is disconnected, and loses it on a restart. After every reconnect the Camel consumer asks the server for its consumer, and subscribes again when its ephemeral consumer is gone:

  • The new consumer starts at the first message the route did not acknowledge, so the route can see again the messages after that one (with ackPolicy=None, after the last message delivered). A message that was not acknowledged and was already delivered maxDeliver times does not count, as the server does not deliver it again.

  • When nothing was delivered yet, a consumer with the deliver policy New (or Last) starts after (or at) the last message of the stream at the subscribe.

  • On a stream with WorkQueue retention, and on a stream that was created again since the route subscribed, the new consumer uses the consumer configuration as it is (from the first message of the new stream for New and Last).

  • When the consumer cannot be checked or created again (for example JetStream is not ready yet after a server restart, or the stream is gone until it is created again), the Camel consumer keeps trying while the route runs, a few times a second apart and then up to every 30 seconds, and logs a WARN after the first attempts.

A durable consumer is not created again: when it is gone (deleted by an administrator, or after its inactiveThreshold), the Camel consumer logs a WARN and keeps its subscription, and messages arrive again when the durable is created again with the same deliver subject.

The consumer is checked only after a reconnect. A consumer that is deleted while the connection stays up (for example with nats consumer rm) is not detected, and the route receives nothing more until it is restarted.