public interface Connection
extends java.lang.AutoCloseable
Each connection you create will result in the creation of a single socket and several threads:
The connection has a status which can be checked using the getStatus
method or watched using a ConnectionListener.
Connections, by default, are configured to try to reconnect to the server if there is a network failure up to
times. You can configure this behavior in the Options.
Moreover, the options allows you to control whether reconnect happens in the same order every time, and the time
to wait if trying to reconnect to the same server over and over.
The list of servers used for connecting is provided by the Options. The list of servers used
during reconnect can be an expanded list. This expansion comes from the connections most recent server. For example,
if you connect to serverA, it can tell the connection "i know about serverB and serverC". If serverA goes down
the client library will try to connect to serverA, serverB and serverC. Now, if the library connects to serverB, it may tell the client
"i know about serverB and serverE". The client's list of servers, available from getServers()
will now be serverA from the initial connect, serverB and serverE, the reference to serverC is lost.
When a connection is closed the thread and socket resources are cleaned up.
All outgoing messages are sent through the connection object using one of the two
publish methods or the request method.
When publishing you can specify a reply to subject which can be retrieved by the receiver to respond.
The request method will handle this behavior itself, but it relies on getting the value out of a Future
so may be less flexible than publish with replyTo set.
Messages can be received in two ways. You can create a Subscription which will allow you to read messages
synchronously using the nextMessage method or you can create a
Dispatcher. The Dispatcher will create a thread to listen for messages on one or more subscriptions.
The Dispatcher groups a set of subscriptions into a single listener thread that calls application code
for each messages.
Applications can use the flush method to check that published messages have
made it to the server. However, this method initiates a round trip to the server and waits for the response so
it should be used sparingly.
The connection provides two listeners via the Options. The ConnectionListener
can be used to listen for lifecycle events. This listener is required for
connectAsynchronously, but otherwise optional. The
ErrorListener provides three callback opportunities including slow consumers, error
messages from the server and exceptions handled by the client library. These listeners can only be set at creation time
using the options.
Note: The publish methods take an array of bytes. These arrays will not be copied. This design choice is based on the common case of strings or objects being converted to bytes. Once a client can be sure a message was received by the NATS server it is theoretically possible to reuse that byte array, but this pattern should be treated as advanced and only used after thorough testing.
| Modifier and Type | Interface and Description |
|---|---|
static class |
Connection.Status
Enum representing the status of a connection
|
| Modifier and Type | Method and Description |
|---|---|
void |
addConnectionListener(@NonNull ConnectionListener connectionListener)
Attach another ConnectionListener.
|
void |
clearLastError()
Clear the last error from the server
|
void |
close()
Close the connection and release all blocking calls like
flush
and nextMessage. |
void |
closeDispatcher(@NonNull Dispatcher dispatcher)
Close a dispatcher.
|
@NonNull Dispatcher |
createDispatcher()
Convenience method to create a dispatcher with no default handler.
|
@NonNull Dispatcher |
createDispatcher(@Nullable MessageHandler handler)
Create a
Dispatcher for this connection. |
@NonNull java.lang.String |
createInbox()
Create a new inbox subject, can be used for directed replies from
subscribers.
|
@NonNull java.util.concurrent.CompletableFuture<java.lang.Boolean> |
drain(@Nullable java.time.Duration timeout)
Drain tells the connection to process in flight messages before closing.
|
void |
flush(@Nullable java.time.Duration timeout)
Flush the connection's buffer of outgoing messages, including sending a
protocol message to and from the server.
|
void |
flushBuffer()
Immediately flushes the underlying connection buffer if the connection is valid.
|
void |
forceReconnect()
Forces reconnect behavior.
|
void |
forceReconnect(@Nullable ForceReconnectOptions options)
Forces reconnect behavior.
|
@Nullable java.net.InetAddress |
getClientInetAddress()
the InetAddress of client as known by the NATS server, otherwise null.
|
@Nullable java.lang.String |
getConnectedUrl()
the url used for the current connection, or null if disconnected
|
@NonNull ConsumerContext |
getConsumerContext(@NonNull java.lang.String streamName,
@NonNull java.lang.String consumerName)
Get a consumer context for a specific named stream and specific named consumer.
|
@NonNull ConsumerContext |
getConsumerContext(@NonNull java.lang.String streamName,
@NonNull java.lang.String consumerName,
@Nullable JetStreamOptions options)
Get a consumer context for a specific named stream and specific named consumer.
|
@Nullable java.lang.String |
getLastError()
the error text from the last error sent by the server to this client
|
long |
getMaxPayload()
MaxPayload returns the size limit that a message payload can have.
|
@NonNull Options |
getOptions()
the read-only options used to create this connection
|
@NonNull ServerInfo |
getServerInfo()
Return the server info object.
|
@NonNull java.util.Collection<java.lang.String> |
getServers()
Return the list of known server urls, including additional servers discovered
after a connection has been established.
|
@NonNull Statistics |
getStatistics()
a wrapper for useful statistics about the connection
|
@NonNull Connection.Status |
getStatus()
Returns the connections current status.
|
@NonNull StreamContext |
getStreamContext(@NonNull java.lang.String streamName)
Get a stream context for a specific stream.
|
@NonNull StreamContext |
getStreamContext(@NonNull java.lang.String streamName,
@Nullable JetStreamOptions options)
Get a stream context for a specific stream
|
@NonNull JetStream |
jetStream()
Gets a context for publishing and subscribing to subjects backed by Jetstream streams
and consumers.
|
@NonNull JetStream |
jetStream(@Nullable JetStreamOptions options)
Gets a context for publishing and subscribing to subjects backed by Jetstream streams
and consumers.
|
@NonNull JetStreamManagement |
jetStreamManagement()
Gets a context for managing Jetstream streams
and consumers.
|
@NonNull JetStreamManagement |
jetStreamManagement(@Nullable JetStreamOptions options)
Gets a context for managing Jetstream streams
and consumers.
|
@NonNull KeyValue |
keyValue(@NonNull java.lang.String bucketName)
Gets a context for working with a Key Value bucket
|
@NonNull KeyValue |
keyValue(@NonNull java.lang.String bucketName,
@Nullable KeyValueOptions options)
Gets a context for working with a Key Value bucket
|
@NonNull KeyValueManagement |
keyValueManagement()
Gets a context for managing Key Value buckets
|
@NonNull KeyValueManagement |
keyValueManagement(@Nullable KeyValueOptions options)
Gets a context for managing Key Value buckets
|
@NonNull ObjectStore |
objectStore(@NonNull java.lang.String bucketName)
Gets a context for working with an Object Store.
|
@NonNull ObjectStore |
objectStore(@NonNull java.lang.String bucketName,
@Nullable ObjectStoreOptions options)
Gets a context for working with an Object Store.
|
@NonNull ObjectStoreManagement |
objectStoreManagement()
Gets a context for managing Object Stores
|
@NonNull ObjectStoreManagement |
objectStoreManagement(ObjectStoreOptions options)
Gets a context for managing Object Stores
|
long |
outgoingPendingBytes()
Get the number of bytes based to be written calculated from the messages in the outgoing queue for this connection.
|
long |
outgoingPendingMessageCount()
Get the number of messages in the outgoing queue for this connection.
|
void |
publish(@NonNull Message message)
Send a message to the specified subject.
|
void |
publish(@NonNull java.lang.String subject,
byte[] body)
Send a message to the specified subject.
|
void |
publish(@NonNull java.lang.String subject,
@Nullable io.nats.client.impl.Headers headers,
byte[] body)
Send a message to the specified subject.
|
void |
publish(@NonNull java.lang.String subject,
@Nullable java.lang.String replyTo,
byte[] body)
Send a request to the specified subject, providing a replyTo subject.
|
void |
publish(@NonNull java.lang.String subject,
@Nullable java.lang.String replyTo,
@Nullable io.nats.client.impl.Headers headers,
byte[] body)
Send a request to the specified subject, providing a replyTo subject.
|
void |
removeConnectionListener(@NonNull ConnectionListener connectionListener)
Detach a ConnectionListioner.
|
@NonNull java.util.concurrent.CompletableFuture<Message> |
request(@NonNull Message message)
Send a request.
|
@Nullable Message |
request(@NonNull Message message,
@Nullable java.time.Duration timeout)
Send a request and returns the reply or null.
|
@NonNull java.util.concurrent.CompletableFuture<Message> |
request(@NonNull java.lang.String subject,
byte[] body)
Send a request.
|
@Nullable Message |
request(@NonNull java.lang.String subject,
byte[] body,
@Nullable java.time.Duration timeout)
Send a request and returns the reply or null.
|
@NonNull java.util.concurrent.CompletableFuture<Message> |
request(@NonNull java.lang.String subject,
@Nullable io.nats.client.impl.Headers headers,
byte[] body)
Send a request.
|
@Nullable Message |
request(@NonNull java.lang.String subject,
@Nullable io.nats.client.impl.Headers headers,
byte[] body,
@Nullable java.time.Duration timeout)
Send a request and returns the reply or null.
|
@NonNull java.util.concurrent.CompletableFuture<Message> |
requestWithTimeout(@NonNull Message message,
@Nullable java.time.Duration timeout)
Send a request.
|
@NonNull java.util.concurrent.CompletableFuture<Message> |
requestWithTimeout(@NonNull java.lang.String subject,
byte[] body,
@Nullable java.time.Duration timeout)
Send a request.
|
@NonNull java.util.concurrent.CompletableFuture<Message> |
requestWithTimeout(@NonNull java.lang.String subject,
@Nullable io.nats.client.impl.Headers headers,
byte[] body,
java.time.Duration timeout)
Send a request.
|
@NonNull java.time.Duration |
RTT()
Calculates the round trip time between this client and the server.
|
@NonNull Subscription |
subscribe(@NonNull java.lang.String subject)
Create a synchronous subscription to the specified subject.
|
@NonNull Subscription |
subscribe(@NonNull java.lang.String subject,
@NonNull java.lang.String queueName)
Create a synchronous subscription to the specified subject and queue.
|
void publish(@NonNull java.lang.String subject,
byte[] body)
nc = Nats.connect()
nc.publish("destination", "message".getBytes("UTF-8"))
where the sender creates a byte array immediately before calling publish.
See publish() for more details on
publish during reconnect.subject - the subject to send the message tobody - the message bodyjava.lang.IllegalStateException - if the reconnect buffer is exceededvoid publish(@NonNull java.lang.String subject,
@Nullable io.nats.client.impl.Headers headers,
byte[] body)
nc = Nats.connect()
Headers h = new Headers().put("key", "value");
nc.publish("destination", h, "message".getBytes("UTF-8"))
where the sender creates a byte array immediately before calling publish.
See publish() for more details on
publish during reconnect.subject - the subject to send the message toheaders - Optional headers to publish with the message.body - the message bodyjava.lang.IllegalStateException - if the reconnect buffer is exceededvoid publish(@NonNull java.lang.String subject,
@Nullable java.lang.String replyTo,
byte[] body)
nc = Nats.connect()
nc.publish("destination", "reply-to", "message".getBytes("UTF-8"))
where the sender creates a byte array immediately before calling publish.
During reconnect the client will try to buffer messages. The buffer size is set
in the connect options, see reconnectBufferSize()
with a default value of 8 * 1024 * 1024 bytes.
If the buffer is exceeded an IllegalStateException is thrown. Applications should use
this exception as a signal to wait for reconnect before continuing.
subject - the subject to send the message toreplyTo - the subject the receiver should send any response tobody - the message bodyjava.lang.IllegalStateException - if the reconnect buffer is exceededvoid publish(@NonNull java.lang.String subject,
@Nullable java.lang.String replyTo,
@Nullable io.nats.client.impl.Headers headers,
byte[] body)
nc = Nats.connect()
Headers h = new Headers().put("key", "value");
nc.publish("destination", "reply-to", h, "message".getBytes("UTF-8"))
where the sender creates a byte array immediately before calling publish.
During reconnect the client will try to buffer messages. The buffer size is set
in the connect options, see reconnectBufferSize()
with a default value of 8 * 1024 * 1024 bytes.
If the buffer is exceeded an IllegalStateException is thrown. Applications should use
this exception as a signal to wait for reconnect before continuing.
subject - the subject to send the message toreplyTo - the subject the receiver should send any response toheaders - Optional headers to publish with the message.body - the message bodyjava.lang.IllegalStateException - if the reconnect buffer is exceededvoid publish(@NonNull Message message)
nc = Nats.connect() nc.publish(NatsMessage.builder()...build())where the sender creates a byte array immediately before calling publish. See
publish() for more details on
publish during reconnect.message - the messagejava.lang.IllegalStateException - if the reconnect buffer is exceeded@NonNull java.util.concurrent.CompletableFuture<Message> request(@NonNull java.lang.String subject, byte[] body)
subject - the subject for the service that will handle the requestbody - the content of the message@NonNull java.util.concurrent.CompletableFuture<Message> request(@NonNull java.lang.String subject, @Nullable io.nats.client.impl.Headers headers, byte[] body)
subject - the subject for the service that will handle the requestheaders - Optional headers to publish with the message.body - the content of the message@NonNull java.util.concurrent.CompletableFuture<Message> requestWithTimeout(@NonNull java.lang.String subject, byte[] body, @Nullable java.time.Duration timeout)
subject - the subject for the service that will handle the requestbody - the content of the messagetimeout - the time to wait for a response. If not supplied a default will be used.@NonNull java.util.concurrent.CompletableFuture<Message> requestWithTimeout(@NonNull java.lang.String subject, @Nullable io.nats.client.impl.Headers headers, byte[] body, java.time.Duration timeout)
subject - the subject for the service that will handle the requestbody - the content of the messageheaders - Optional headers to publish with the message.timeout - the time to wait for a response@NonNull java.util.concurrent.CompletableFuture<Message> request(@NonNull Message message)
The Message object allows you to set a replyTo, but in requests, the replyTo is reserved for internal use as the address for the server to respond to the client with the consumer's reply.
message - the message@NonNull java.util.concurrent.CompletableFuture<Message> requestWithTimeout(@NonNull Message message, @Nullable java.time.Duration timeout)
The Message object allows you to set a replyTo, but in requests, the replyTo is reserved for internal use as the address for the server to respond to the client with the consumer's reply.
message - the messagetimeout - the time to wait for a response@Nullable Message request(@NonNull java.lang.String subject, byte[] body, @Nullable java.time.Duration timeout) throws java.lang.InterruptedException
request() with
the timeout and handling the ExecutionException and TimeoutException.subject - the subject for the service that will handle the requestbody - the content of the messagetimeout - the time to wait for a responsejava.lang.InterruptedException - if one is thrown while waiting, in order to propagate it up@Nullable Message request(@NonNull java.lang.String subject, @Nullable io.nats.client.impl.Headers headers, byte[] body, @Nullable java.time.Duration timeout) throws java.lang.InterruptedException
request() with
the timeout and handling the ExecutionException and TimeoutException.subject - the subject for the service that will handle the requestheaders - Optional headers to publish with the message.body - the content of the messagetimeout - the time to wait for a responsejava.lang.InterruptedException - if one is thrown while waiting, in order to propagate it up@Nullable Message request(@NonNull Message message, @Nullable java.time.Duration timeout) throws java.lang.InterruptedException
request() with
the timeout and handling the ExecutionException and TimeoutException.
The Message object allows you to set a replyTo, but in requests, the replyTo is reserved for internal use as the address for the server to respond to the client with the consumer's reply.
message - the messagetimeout - the time to wait for a responsejava.lang.InterruptedException - if one is thrown while waiting, in order to propagate it up@NonNull Subscription subscribe(@NonNull java.lang.String subject)
Use the nextMessage
method to read messages for this subscription.
See createDispatcher for
information about creating an asynchronous subscription with callbacks.
As of 2.6.1 this method will throw an IllegalArgumentException if the subject contains whitespace.
subject - the subject to subscribe to@NonNull Subscription subscribe(@NonNull java.lang.String subject, @NonNull java.lang.String queueName)
Use the nextMessage method to read
messages for this subscription.
See createDispatcher for
information about creating an asynchronous subscription with callbacks.
As of 2.6.1 this method will throw an IllegalArgumentException if either string contains whitespace.
subject - the subject to subscribe toqueueName - the queue group to join@NonNull Dispatcher createDispatcher(@Nullable MessageHandler handler)
Dispatcher for this connection. The dispatcher can group one
or more subscriptions into a single callback thread. All messages go to the
same MessageHandler.
Use the Dispatcher's Dispatcher.subscribe(String) and
Dispatcher.subscribe(String, String) methods to add subscriptions.
nc = Nats.connect()
d = nc.createDispatcher((m) -> System.out.println(m)).subscribe("hello");
handler - The target for the messages. If the handler is null, subscribing without
using its API that accepts a handler will discard messages.@NonNull Dispatcher createDispatcher()
void closeDispatcher(@NonNull Dispatcher dispatcher)
Once closed the dispatcher will throw an exception on subsequent subscribe or unsubscribe calls.
dispatcher - the dispatcher to closevoid addConnectionListener(@NonNull ConnectionListener connectionListener)
The ConnectionListener will only receive Connection events arriving after it has been attached. When a Connection event is raised, the invocation order and parallelism of multiple ConnectionListeners is not specified.
connectionListener - the ConnectionListener to attach. A null listener is a no-opvoid removeConnectionListener(@NonNull ConnectionListener connectionListener)
connectionListener - the ConnectionListener to detachvoid flush(@Nullable java.time.Duration timeout)
throws java.util.concurrent.TimeoutException,
java.lang.InterruptedException
timeout - The time to wait for the flush to succeed, pass 0 or null to wait forever.java.util.concurrent.TimeoutException - if the timeout is exceededjava.lang.InterruptedException - if the underlying thread is interrupted@NonNull java.util.concurrent.CompletableFuture<java.lang.Boolean> drain(@Nullable java.time.Duration timeout)
throws java.util.concurrent.TimeoutException,
java.lang.InterruptedException
timeout - The time to wait for the drain to succeed, pass 0 or null to wait
forever. Drain involves moving messages to and from the server
so a very short timeout is not recommended. If the timeout is reached before
the drain completes, the connection is simply closed, which can result in message
loss.java.lang.InterruptedException - if the thread is interruptedjava.util.concurrent.TimeoutException - if the initial flush times outvoid close()
throws java.lang.InterruptedException
flush
and nextMessage.
If close() is called after drain it will wait up to the connection timeout
to return, but it will not initiate a close. The drain takes precedence and will initiate the close.close in interface java.lang.AutoCloseablejava.lang.InterruptedException - if the thread, or one owned by the connection is interrupted during the close@NonNull Connection.Status getStatus()
long getMaxPayload()
@NonNull java.util.Collection<java.lang.String> getServers()
@NonNull Statistics getStatistics()
@NonNull Options getOptions()
@NonNull ServerInfo getServerInfo()
ServerInfo.EMPTY_INFO
before a connection is made, and will represent the last connected server once connected and while disconnected
until a new connection is made.@Nullable java.lang.String getConnectedUrl()
@Nullable java.net.InetAddress getClientInetAddress()
@Nullable java.lang.String getLastError()
void clearLastError()
@NonNull java.lang.String createInbox()
void flushBuffer()
throws java.io.IOException
java.io.IOException - if the connection flush failsvoid forceReconnect()
throws java.io.IOException,
java.lang.InterruptedException
ForceReconnectOptions.java.io.IOException - the forceReconnect failsjava.lang.InterruptedException - the connection is not connectedvoid forceReconnect(@Nullable ForceReconnectOptions options) throws java.io.IOException, java.lang.InterruptedException
ForceReconnectOptions.options - options for how the forceReconnect works.java.io.IOException - the forceReconnect failsjava.lang.InterruptedException - the connection is not connected@NonNull java.time.Duration RTT()
throws java.io.IOException
java.io.IOException - various IO exception such as timeout or interruption@NonNull StreamContext getStreamContext(@NonNull java.lang.String streamName) throws java.io.IOException, JetStreamApiException
Recommended: See getStreamContext(String, JetStreamOptions)
streamName - the stream for the contextjava.io.IOException - covers various communication issues with the NATS
server such as timeout or interruptionJetStreamApiException - the request had an error related to the data@NonNull StreamContext getStreamContext(@NonNull java.lang.String streamName, @Nullable JetStreamOptions options) throws java.io.IOException, JetStreamApiException
Recommended: StreamContext and ConsumerContext are the preferred way to interact with existing streams and consume from streams.
JetStreamManagement should be used to create streams and consumers. ConsumerContext.consume() supports both push and pull consumers transparently.
nc = Nats.connect();
StreamContext streamContext = nc.getStreamContext("my-stream");
ConsumerContext consumerContext = streamContext.getConsumerContext("my-consumer");
// Or directly:
// ConsumerContext consumerContext = nc.getConsumerContext("my-stream", "my-consumer");
consumerContext.consume(
msg -> {
System.out.println(" Received " + msg.getSubject());
msg.ack();
});
streamName - the stream for the contextoptions - JetStream options. If null, default / no options are used.java.io.IOException - covers various communication issues with the NATS
server such as timeout or interruptionJetStreamApiException - the request had an error related to the data@NonNull ConsumerContext getConsumerContext(@NonNull java.lang.String streamName, @NonNull java.lang.String consumerName) throws java.io.IOException, JetStreamApiException
Recommended: See getStreamContext(String, JetStreamOptions)
streamName - the name of the streamconsumerName - the name of the consumerjava.io.IOException - covers various communication issues with the NATS
server such as timeout or interruptionJetStreamApiException - the request had an error related to the data@NonNull ConsumerContext getConsumerContext(@NonNull java.lang.String streamName, @NonNull java.lang.String consumerName, @Nullable JetStreamOptions options) throws java.io.IOException, JetStreamApiException
Recommended: See getStreamContext(String, JetStreamOptions)
streamName - the name of the streamconsumerName - the name of the consumeroptions - JetStream options. If null, default / no options are used.java.io.IOException - covers various communication issues with the NATS
server such as timeout or interruptionJetStreamApiException - the request had an error related to the data@NonNull JetStream jetStream() throws java.io.IOException
java.io.IOException - various IO exception such as timeout or interruption@NonNull JetStream jetStream(@Nullable JetStreamOptions options) throws java.io.IOException
options - JetStream options. If null, default / no options are used.java.io.IOException - covers various communication issues with the NATS
server such as timeout or interruption@NonNull JetStreamManagement jetStreamManagement() throws java.io.IOException
java.io.IOException - various IO exception such as timeout or interruption@NonNull JetStreamManagement jetStreamManagement(@Nullable JetStreamOptions options) throws java.io.IOException
options - JetStream options. If null, default / no options are used.java.io.IOException - covers various communication issues with the NATS
server such as timeout or interruption@NonNull KeyValue keyValue(@NonNull java.lang.String bucketName) throws java.io.IOException
bucketName - the bucket namejava.io.IOException - various IO exception such as timeout or interruption@NonNull KeyValue keyValue(@NonNull java.lang.String bucketName, @Nullable KeyValueOptions options) throws java.io.IOException
bucketName - the bucket nameoptions - KeyValue options. If null, default / no options are used.java.io.IOException - various IO exception such as timeout or interruption@NonNull KeyValueManagement keyValueManagement() throws java.io.IOException
java.io.IOException - various IO exception such as timeout or interruption@NonNull KeyValueManagement keyValueManagement(@Nullable KeyValueOptions options) throws java.io.IOException
options - KeyValue options. If null, default / no options are used.java.io.IOException - various IO exception such as timeout or interruption@NonNull ObjectStore objectStore(@NonNull java.lang.String bucketName) throws java.io.IOException
bucketName - the bucket namejava.io.IOException - various IO exception such as timeout or interruption@NonNull ObjectStore objectStore(@NonNull java.lang.String bucketName, @Nullable ObjectStoreOptions options) throws java.io.IOException
bucketName - the bucket nameoptions - ObjectStore options. If null, default / no options are used.java.io.IOException - various IO exception such as timeout or interruption@NonNull ObjectStoreManagement objectStoreManagement() throws java.io.IOException
java.io.IOException - various IO exception such as timeout or interruption@NonNull ObjectStoreManagement objectStoreManagement(ObjectStoreOptions options) throws java.io.IOException
options - ObjectStore options. If null, default / no options are used.java.io.IOException - various IO exception such as timeout or interruptionlong outgoingPendingMessageCount()
long outgoingPendingBytes()