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 gnatsd 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 |
Modifier and Type | Method and Description |
---|---|
void |
close()
Close the connection and release all blocking calls like
flush
and nextMessage . |
void |
closeDispatcher(Dispatcher dispatcher)
Close a dispatcher.
|
Dispatcher |
createDispatcher(MessageHandler handler)
Create a
Dispatcher for this connection. |
java.util.concurrent.CompletableFuture<java.lang.Boolean> |
drain(java.time.Duration timeout)
Drain tells the connection to process in flight messages before closing.
|
void |
flush(java.time.Duration timeout)
Flush the connection's buffer of outgoing messages, including sending a
protocol message to and from the server.
|
java.lang.String |
getConnectedUrl() |
java.lang.String |
getLastError() |
long |
getMaxPayload()
MaxPayload returns the size limit that a message payload can have.
|
Options |
getOptions() |
java.util.Collection<java.lang.String> |
getServers()
Return the list of known server urls, including additional servers discovered
after a connection has been established.
|
Statistics |
getStatistics() |
Connection.Status |
getStatus()
Returns the connections current status.
|
void |
publish(java.lang.String subject,
byte[] body)
Send a message to the specified subject.
|
void |
publish(java.lang.String subject,
java.lang.String replyTo,
byte[] body)
Send a request to the specified subject, providing a replyTo subject.
|
java.util.concurrent.CompletableFuture<Message> |
request(java.lang.String subject,
byte[] data)
Send a request.
|
Message |
request(java.lang.String subject,
byte[] data,
java.time.Duration timeout)
Send a request and returns the reply or null.
|
Subscription |
subscribe(java.lang.String subject)
Create a synchronous subscription to the specified subject.
|
Subscription |
subscribe(java.lang.String subject,
java.lang.String queueName)
Create a synchronous subscription to the specified subject and queue.
|
void publish(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.
subject
- the subject to send the message tobody
- the message bodyvoid publish(java.lang.String subject, 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.
subject
- the subject to send the message toreplyTo
- the subject the receiver should send the response tobody
- the message bodyjava.util.concurrent.CompletableFuture<Message> request(java.lang.String subject, byte[] data)
subject
- the subject for the service that will handle the requestdata
- the content of the messageMessage request(java.lang.String subject, byte[] data, 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 requestdata
- the content of the messagetimeout
- the time to wait for a responsejava.lang.InterruptedException
- if one is thrown while waiting, in order to propogate it upSubscription subscribe(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.
subject
- the subject to subscribe toSubscription subscribe(java.lang.String subject, 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.
subject
- the subject to subscribe toqueueName
- the queue group to joinDispatcher createDispatcher(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 messagesvoid closeDispatcher(Dispatcher dispatcher)
Once closed the dispatcher will throw an exception on subsequent subscribe or unsubscribe calls.
dispatcher
- the dispatcher to closevoid flush(java.time.Duration timeout) throws java.util.concurrent.TimeoutException, java.lang.InterruptedException
timeout
- The time to wait for the flush to succeed, pass 0 to wait
forever.java.util.concurrent.TimeoutException
- if the timeout is exceededjava.lang.InterruptedException
- if the underlying thread is interruptedjava.util.concurrent.CompletableFuture<java.lang.Boolean> drain(java.time.Duration timeout) throws java.util.concurrent.TimeoutException, java.lang.InterruptedException
timeout
- The time to wait for the drain to succeed, pass 0 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.AutoCloseable
java.lang.InterruptedException
- if the thread, or one owned by the connection is interrupted during the closeConnection.Status getStatus()
long getMaxPayload()
java.util.Collection<java.lang.String> getServers()
Statistics getStatistics()
Options getOptions()
java.lang.String getConnectedUrl()
java.lang.String getLastError()